早期 Google Translate 提供無需金鑰的網頁端接口,利用此特性可快速構建輕量級翻譯工具。本文分享一個 PHP 命令行腳本,支援管道輸入、參數指定語言、多 IP 輪換,適合批量文本翻譯或集成至自動化流程。
<?php
/**
* Google Translate 网页接口封装
* 注意:该非官方接口可能随时失效,生产环境建议使用官方 Cloud Translation API
*/
class Google_API_Translator
{
public $url = 'https://translate.google.com/translate_t';
public $text = '';
public $out = '';
public $ip = ''; // 指定出口 IP(多网卡场景)
public function setText($text) { $this->text = $text; }
public function translate($from = 'auto', $to = 'zh-CN')
{
$this->out = '';
$html = $this->postPage($this->url, $this->text, $from, $to);
// 解析返回页面中的翻译结果
if (preg_match('/]*id=["\']result_box["\'][^>]*>(.*?)<\/span>/is', $html, $matches)) {
$this->out = strip_tags($matches[1]);
}
return $this->out;
}
private function postPage($url, $text, $from, $to)
{
if (empty($url) || empty($text)) return '';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'hl' => 'zh-CN',
'langpair' => "$from|$to",
'ie' => 'UTF-8',
'text' => $text,
]),
]);
if (!empty($this->ip) && filter_var($this->ip, FILTER_VALIDATE_IP)) {
curl_setopt($ch, CURLOPT_INTERFACE, $this->ip);
}
$html = curl_exec($ch);
curl_close($ch);
return $html ?: '';
}
}
// ====== CLI 入口 ======
$from = $_REQUEST['fromlan'] ?? 'en';
$to = $_REQUEST['tolan'] ?? 'zh-CN';
// 支持命令行参数:php gtranslate.php "Hello World"
$text = $argv[1] ?? ($_REQUEST['article'] ?? '');
$translator = new Google_API_Translator();
if (!empty($_REQUEST['ip'])) $translator->ip = $_REQUEST['ip'];
// 编码转换(脚本文件若为 GBK 保存)
$text = iconv('GBK', 'UTF-8', $text);
$text = str_replace('{enter}', "\r\n", $text);
$translator->setText($text);
$result = $translator->translate($from, $to);
echo "----------- 翻譯結果 ---------------\n";
echo iconv('UTF-8', 'GBK', $result) . "\n";
gtranslate(無副檔名)。chmod +x gtranslateln -s /path/to/gtranslate /usr/local/bin/gtranslate$ gtranslate Hello World
----------- 翻譯結果 ---------------
世界您好
$ gtranslate -r 中國 # 反向翻譯(需腳本內部處理 -r 參數)
China
iconv 轉換方向必須一致,建議統一使用 UTF-8 保存源碼。