php調用google在線翻譯功能
從中文到英語
class Google_API_translator {
public $out = "";
function translate() {
$this->out = "";
$text = urlencode("計算機");//要翻譯的單詞
$google_translator_url = "http://translate.google.com/translate_a/t?client=t&text=".$text."&sl=zh_CN&tl=en";
echo $google_translator_url;
$gphtml = $this->postPage(array("url" => $google_translator_url));
$this->out = $gphtml;
return $this->out;
}
function postPage($opts) {
$html = "";
if($opts["url"] != "") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $opts["url"]);
$html = curl_exec($ch);
if(curl_errno($ch)) $html = "";
curl_close ($ch);
}
return $html;
}
}
$g = new Google_API_translator();
$g->translate();
從英語到中文
class Google_API_translator {
public $out = "";
function translate() {
$this->out = "";
$text = urlencode("computer");//要翻譯的單詞
$google_translator_url = "http://translate.google.com/translate_a/t?client=t&text=".$text."&sl=en&tl=zh_CN";
//拼湊google翻譯的api url
$gphtml = $this->postPage(array("url" => $google_translator_url));
$this->out = $gphtml;
return $this->out;
}
function postPage($opts) {
$html = "";
if($opts["url"] != "") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $opts["url"]);
$html = curl_exec($ch);
if(curl_errno($ch)) $html = "";
curl_close ($ch);
}
return $html;
}
}
$g = new Google_API_translator();
$g->translate();
很完美,返回的結果中沒有任何編碼問題。從google返回的中文編碼完全正確。