Class Google_API_translator {
Public $ out = "";
Function translate (){
$ This-> out = "";
$ Text = urlencode ("computer"); // The word to be translated.
$ Google_translator_url = "http://translate.google.com/translate_a/t? Client = t & text = ". $ text." & sl = en & tl = zh_CN ";
// Splice the google translation 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 ();
Perfect. There is no encoding problem in the returned results. The Chinese code returned from google is completely correct.
Next, can I perform reverse translation from Chinese to English?
Class Google_API_translator {
Public $ out = "";
Function translate (){
$ This-> out = "";
$ Text = urlencode ("computer"); // The word to be translated.
$ 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 ();
If the problem occurs, a garbled code is returned. What's strange is that this time I accept the English words sent from google. How can I get a code error?
Is php's curl unable to send unicode encoding or is there a problem in google's acceptance process? Copy the PHP content to the clipboard. PHP code: echo $ google_translator_url;
The obtained url is to copy the PHP content to the clipboard PHP code: http://translate.google.com/translate_a/t? Client = t & text = % E8 % AE % A1 % E7 % AE % 97% E6 % 9C % BA & sl = zh_CN & tl = en
Directly enter the url in the address bar of the browser. No problem occurs (IE and Firefox can pass ).
Assume that there is a parsing problem during unicode transfer, and the url of the api is changed, change "& sl = zh_CN & tl = en" to a completely incorrect parameter to copy the PHP content to the clipboard PHP code: http://translate.google.com/translate_a/t? Client = t & text = % E8 % AE % A1 % E7 % AE % 97% E6 % 9C % BA & sl = en & tl = en
It is strange that this php page can accept Chinese strings sent back from google, but it cannot display the results sent by google using the correct encoding parameter.