[Code] [PHP] code/* Google translate PHP interface 02 * official documents 2009-03-2803 * documents _
/* Google translate PHP interface
* Official documents
* Http://blog.csdn.net/aprin/
* Note: If the translation text is UTF-8 encoded, 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 the 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, which is useless here.
* Langpair-src lang to dest lang
* How is the ie-urlencode encoded?
* Text-the text to be translated
*/
$ Fields = array ('hl = zh-cn', 'langpair = zh-CN | EN', '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;
?>