百度翻譯開放平台提供通用翻譯 API,支援 200+ 語言互譯。接入需註冊開發者賬號,獲取 APP ID 與 密鑰,請求需簽名驗證。
| 參數 | 說明 |
|---|---|
| q | 待翻譯文本(UTF-8,長度 ≤ 6000 字節) |
| from | 源語言代碼(auto 自動檢測) |
| to | 目標語言代碼 |
| appid | 應用 ID |
| salt | 隨機數(建議時間戳+隨機數) |
| sign | MD5(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());
}
?>
API 強制要求 UTF-8。若源文本為 GBK/GB2312,需先轉碼:
$text = mb_convert_encoding($text, 'UTF-8', 'GBK');
| 錯誤碼 | 含義 | 處理建議 |
|---|---|---|
| 52001 | 請求超時 | 重試、增加超時時間 |
| 52002 | 系統錯誤 | 指數退避重試 |
| 52003 | 未授權用戶 | 檢查 APP ID/密鑰、賬號餘額 |
| 54000 | 必填參數缺失 | 檢查參數構造 |
| 54001 | 簽名錯誤 | 核對加密順序、編碼 |
| 54003 | 訪問頻率受限 | 降低並發、增加間隔 |
| 58000 | 客戶端 IP 非法 | 在控制台添加服務器 IP 白名單 |
| 服務 | 免費額度 | 優勢 | 劣勢 |
|---|---|---|---|
| 百度翻譯 | 100 萬字符/月 | 中文優化好、價格低 | 需備案域名、IP 白名單 |
| Google Cloud Translation | 50 萬字符/月 | 語言最全、質量高 | 需海外支付、價格高 |
| 騰訊翻譯 | 500 萬字符/月 | 免費額度大、無需備案 | 小語種較弱 |
| DeepL API | 50 萬字符/月 | 歐洲語系質量極高 | 不支援中文、價格高 |
<?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 緩存高頻翻譯結果,大幅降低成本與延遲。