Google translation API (PHPAPI)-PHP source code

Source: Internet
Author: User
Google translation API (PHPAPI)
/* Google translate the 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 =" "; // Translation 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 result $ 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 ($ u Rl! = "" & $ 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, useless here. * How is the langpair-src lang to dest lang * ie-urlencode encoded? * Text-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 Ja Va !"); $ 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.