PHP寫的Google翻譯API
2008/01/21
最近由於要翻譯大量的文字,並且要翻譯多種語言,Google Translate是個不錯的選擇,但是這麼多的文字及這麼多的語言種類,用手工來一個一個翻譯的話,我估計我會死得直直的。
於是下了Google translate API,但是這個API卻是JS的,用起來非常的不方便。在Google及百度上搜了大半天找到些PHP寫的翻譯類,拿下來用了,發現這些代碼都是 Ctrl+C和Ctrl+V過來的,不是不能用就是反翻譯時就出現亂碼。於是又回頭研究Google 的JS API,在這個API中發現了一個可以讓我高興大半天的URL,把它抽出來,再用到PHP的CURL來請求,嘻嘻,竟然成功了。下面把這個類帖出來供大家分享。
/**
* Google翻譯的API
* Author@ Eric Wei
*/
class Google_translate_API
{
public $out = "";
public $text = "";
public $opts = array("text" => "", "language_pair" => "");
function setValues($text,$fromLanguage,$toLanguage)
{
if($text != "")
$this->opts["text"] = $text;
if($fromLanguage != "" && $toLanguage != "")
$this->opts["language_pair"] = $fromLanguage."|".$toLanguage;
}
function translate()
{
$this->out = "";
if (strlen($this->opts['text']) > 500)
{
$str1 = cSubStr($this->opts['text'],0,480);
$str2 = cSubStr($this->opts['text'],480,(strlen($this->opts['text']-480)));
$google_translator_url1 = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($str1)."&langpair=".urlencode($this->opts['language_pair'])."";
$google_translator_url2 = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($str2)."&langpair=".urlencode($this->opts['language_pair'])."";
$response1 = $this->postPage(array("url" => $google_translator_url1));
$response2 = $this->postPage(array("url" => $google_translator_url2));
$resValues = $response1['responseData']['translatedText'].$response2['responseData']['translatedText'];
}
else
{
$google_translator_url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=".urlencode($this->opts['text'])."&langpair=".urlencode($this->opts['language_pair'])."";
$response = $this->postPage(array("url" => $google_translator_url));
$resValues = $response['responseData']['translatedText'];
}
$this->out = $resValues;
return $this->out;
}
function postPage($opts)
{
$response = "";
if($opts["url"] != "") {
$ch = curl_init($opts["url"]);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if(curl_errno($ch))
$response = "";
curl_close($ch);
$decoded = json_decode( $response, true );
}
return $decoded;
}
}
?>
此API有一個缺點是,發送給翻譯的字符串不能大於500個字符長度,此方法還待解決。
用法:
<?php
$tran = Google_translate_API();
$tran->setValues("China","en","zh-CN"); //第一個參數為要翻譯的文字,第二、三個參數分別為原語言和翻譯後語言
$res = $tran->translate();
echo $res;
?>
簡易的函式
但如果只是要一個簡易的快速翻譯函式,其實這樣寫就可以了:
/** * Google翻譯的function
* Author@ InspireGate * $text = '要翻譯的文字' //不能超過500字 * $origLan = '來源語言' * $transLan = '翻譯語言' * * Example: * echo gTranslate ('工具','zh-TW','en') ; * * Result: Tools */
function gTranslate ($text,$origLan,$transLan) { $url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='.urlencode($text) ; $url .= '&langpair='.$origLan.'|'.$transLan ; $response = file_get_contents($url); $decoded = json_decode( $response, true ); return $decoded['responseData']['translatedText'] ; }