PHP Google's translate API code

Source: Internet
Author: User

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 ..

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.