PHP Google's Translate API code

Source: Internet
Author: User
Tags urlencode

CODE:

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;
}
}
?>

Use of the time

CODE:

$g = new Google_API_translator();
$g->setOpts(array("text" => "Cjjer是天才", "language_pair" => "zh-CN|en"));
$g->translate();
echo $g->out;
?>

That's it, output: Cjjer is genius

PHP is here, see some of the students part of the code. specifically forgotten.

This piece of code is not good ... But it can be used, too lazy to manage.

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.