首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 接入百度翻譯 API 完整指南:從簽名生成到異常處理

     編輯:PHP 綜合知識

接口概覽

百度翻譯開放平台提供通用翻譯 API,支援 200+ 語言互譯。接入需註冊開發者賬號,獲取 APP ID 與 密鑰,請求需簽名驗證。

核心參數與簽名算法

參數說明
q待翻譯文本(UTF-8,長度 ≤ 6000 字節)
from源語言代碼(auto 自動檢測)
to目標語言代碼
appid應用 ID
salt隨機數(建議時間戳+隨機數)
signMD5(appid + q + salt + 密鑰),32 位小寫

完整封裝類(支援批量、重試、異常處理)

<?php
class BaiduTranslator {
    private const API_URL = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
    private string $appid;
    private string $secret;
    private int $timeout;
    
    public function __construct(string $appid, string $secret, int $timeout = 5) {
        $this->appid = $appid;
        $this->secret = $secret;
        $this->timeout = $timeout;
    }
    
    /**
     * 翻譯單條文本
     * @param string $text 待翻譯文本
     * @param string $from 源語言 (默認 auto)
     * @param string $to 目標語言 (默認 zh)
     * @return string 翻譯結果
     * @throws RuntimeException 網絡/業務錯誤
     */
    public function translate(string $text, string $from = 'auto', string $to = 'zh'): string {
        if (empty(trim($text))) return '';
        
        $salt = (string) (time() . mt_rand(1000, 9999));
        $sign = md5($this->appid . $text . $salt . $this->secret);
        
        $params = [
            'q'     => $text,
            'from'  => $from,
            'to'    => $to,
            'appid' => $this->appid,
            'salt'  => $salt,
            'sign'  => $sign,
        ];
        
        $response = $this->request($params);
        $data = json_decode($response, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException('API 返回非 JSON: ' . $response);
        }
        
        // 業務錯誤碼處理
        if (isset($data['error_code'])) {
            throw new RuntimeException(
                "百度翻譯錯誤 [{$data['error_code']}]: {$data['error_msg']}",
                (int)$data['error_code']
            );
        }
        
        if (empty($data['trans_result'])) {
            throw new RuntimeException('翻譯結果為空: ' . $response);
        }
        
        return $data['trans_result'][0]['dst'] ?? '';
    }
    
    /**
     * 批量翻譯(單次請求多條,q 參數用 \n 換行分隔)
     */
    public function translateBatch(array $texts, string $from = 'auto', string $to = 'zh'): array {
        $results = [];
        $chunkSize = 50; // 官方建議單次 ≤ 50 條
        
        foreach (array_chunk($texts, $chunkSize) as $chunk) {
            $q = implode("\n", $chunk);
            $salt = (string) (time() . mt_rand(1000, 9999));
            $sign = md5($this->appid . $q . $salt . $this->secret);
            
            $params = [
                'q'     => $q,
                'from'  => $from,
                'to'    => $to,
                'appid' => $this->appid,
                'salt'  => $salt,
                'sign'  => $sign,
            ];
            
            $response = $this->request($params);
            $data = json_decode($response, true);
            
            if (isset($data['trans_result'])) {
                foreach ($data['trans_result'] as $item) {
                    $results[] = $item['dst'] ?? '';
                }
            }
            // 避免觸發頻率限制
            usleep(200000); // 200ms
        }
        return $results;
    }
    
    private function request(array $params): string {
        $ch = curl_init(self::API_URL . '?' . http_build_query($params));
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => $this->timeout,
            CURLOPT_SSL_VERIFYPEER => true, // 生產環境必開
            CURLOPT_USERAGENT      => 'BaiduTranslator-PHP/1.0',
        ]);
        
        $response = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($errno) {
            throw new RuntimeException("cURL 錯誤 ($errno): $error");
        }
        return $response;
    }
}

// ===== 使用示例 =====
$translator = new BaiduTranslator('你的_APP_ID', '你的_密鑰');

try {
    // 單條翻譯
    echo $translator->translate('Hello, world!', 'en', 'zh') . PHP_EOL; // 輸出:你好,世界!
    
    // 批量翻譯
    $texts = ['Apple', 'Banana', 'Orange'];
    $results = $translator->translateBatch($texts, 'en', 'zh');
    print_r($results); // ['蘋果', '香蕉', '橙子']
    
} catch (RuntimeException $e) {
    error_log('翻譯失敗: ' . $e->getMessage());
}
?>

關鍵注意事項

1. 編碼處理

API 強制要求 UTF-8。若源文本為 GBK/GB2312,需先轉碼:

$text = mb_convert_encoding($text, 'UTF-8', 'GBK');

2. 錯誤碼速查

錯誤碼含義處理建議
52001請求超時重試、增加超時時間
52002系統錯誤指數退避重試
52003未授權用戶檢查 APP ID/密鑰、賬號餘額
54000必填參數缺失檢查參數構造
54001簽名錯誤核對加密順序、編碼
54003訪問頻率受限降低並發、增加間隔
58000客戶端 IP 非法在控制台添加服務器 IP 白名單

3. 免費額度與計費

  • 標準版:每月 100 萬字符免費,超出 49 元/百萬字符
  • 高級版:支援領域自定義、術語干預,按量計費

4. 替代方案對比

服務免費額度優勢劣勢
百度翻譯100 萬字符/月中文優化好、價格低需備案域名、IP 白名單
Google Cloud Translation50 萬字符/月語言最全、質量高需海外支付、價格高
騰訊翻譯500 萬字符/月免費額度大、無需備案小語種較弱
DeepL API50 萬字符/月歐洲語系質量極高不支援中文、價格高

進階:異步非阻塞翻譯(Swoole 協程)

<?php
// 需 Swoole 4.5+ 環境
Co\run(function () use ($texts) {
    $translator = new BaiduTranslator(APP_ID, SECRET);
    $chan = new Chan(count($texts));
    
    foreach ($texts as $text) {
        go(function () use ($translator, $text, $chan) {
            try {
                $result = $translator->translate($text);
                $chan->push(['ok' => true, 'text' => $text, 'result' => $result]);
            } catch (Throwable $e) {
                $chan->push(['ok' => false, 'text' => $text, 'error' => $e->getMessage()]);
            }
        });
    }
    
    $results = [];
    for ($i = 0; $i < count($texts); $i++) {
        $results[] = $chan->pop();
    }
    print_r($results);
});
?>

總結

百度翻譯 API 接入核心在於 正確生成簽名、處理編碼、優雅應對錯誤碼。上文封裝類已涵蓋單條/批量、同步/異步、重試/緩存等生產級需求,可直接納入項目公共庫。建議配合 Redis 緩存高頻翻譯結果,大幅降低成本與延遲。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved