Create an ansi php file and create a class:
Copy codeThe Code is as follows:
Header ("Content-Type: text/html; charset = UTF-8 ");
Class Google_API_translator {
Public $ opts = array ("text" => "", "language_pair" => "en | it ");
Public $ out = "";
Function setOpts ($ opts ){
If ($ opts ["text"]! = "") $ This-> opts ["text"] = $ opts ["text"];
If ($ opts ["language_pair"]! = "") $ This-> opts ["language_pair"] = $ opts ["language_pair"];
}
Function translate (){
$ This-> out = "";
$ Google_translator_url = "http://translate.google.com/translate_t? Langpair = ". urlencode ($ this-> opts [" language_pair "])." &; ";
$ Google_translator_data. = "text =". urlencode ($ this-> opts ["text"]);
$ Gphtml = $ this-> postPage (array ("url" => $ google_translator_url, "data" => $ google_translator_data ));
$ Out = substr ($ gphtml, strpos ($ gphtml ,"
"));
$ Out = substr ($ out, 29 );
$ Out = substr ($ out, 0, strpos ($ out ,"
"));
$ This-> out = utf8_encode ($ out );
Return $ this-> out;
}
Function postPage ($ opts ){
$ Html = '';
If ($ opts ["url"]! = "" & $ Opts ["data"]! = ""){
$ Ch = curl_init ($ opts ["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 );
Curl_setopt ($ ch, CURLOPT_POST, 1 );
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ opts ["data"]);
$ Html = curl_exec ($ ch );
If (curl_errno ($ ch) $ html = "";
Curl_close ($ ch );
}
Return $ html;
}
}
?>
When using
Copy codeThe Code is as follows:
$ G = new Google_API_translator ();
$ G-> setOpts (array ("text" => "Cjjer is a genius", "language_pair" => "zh-CN | en "));
$ G-> translate ();
Echo $ g-> out;
?>
The output is: Cjjer is genius.
For PHP, see some of the code of some students. I forgot the details.
This code is not good... But it can be used. You are too lazy to worry about it ..