Google translation API (PHPAPI)

Source: Internet
Author: User
[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;

?>

 

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.