/* Google translation PHP interface
* Official Written 2009-03-28
* http://blog.csdn.net/aprin/
* Note: If the translated text is UTF-8 encoding, delete the mb_convert_encoding function
*/
Class Google_api_translator {
Public $url = "http://translate.google.com/translate_t";
Public $text = "";//Translate text
Public $out = ""; Translation output
function SetText ($text) {
$this->text = $text;
}
function translate () {
$this->out = "";
$gphtml = $this->postpage ($this->url, $this->text);
Extract translation Results
$out = substr ($gphtml, Strpos ($gphtml, "
“));
$out = substr ($out, 29);
$out = substr ($out, 0, Strpos ($out, "
));
$this->out = $out;
return $this->out;
}
function Postpage ($url, $text) {
$html = ";
if ($url!= "" && $text!= "") {
$ch = Curl_init ($url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, 1);
curl_setopt ($ch, curlopt_followlocation, 1);
curl_setopt ($ch, Curlopt_timeout, 15);
/*
*hl– interface language, here is useless.
*langpair–src Lang to dest Lang
*ie–urlencode's Coding method?
*text– the text to be translated
*/
$fields = Array (' HL=ZH-CN ', ' Langpair=zh-cnen ', ' ie=utf-8′ ', ' text= ') UrlEncode (mb_convert_encoding ($text, ' utf-8′, ') gb2312′)));
curl_setopt ($ch, Curlopt_post, 1);
curl_setopt ($ch, Curlopt_postfields, Implode (' & ', $fields));
$html = curl_exec ($ch);
if (Curl_errno ($ch)) $html = "";
Curl_close ($ch);
}
return $html;
}
}
Just for Test
$g = new Google_api_translator ();
$g->settext ("I love php100!");
$g->translate ();
Echo $g->out;
?>