您的位置:首页 > 编程语言 > PHP开发

Google Translate API of PHP GOOGLE翻译PHP 接口

2009-01-19 17:07 447 查看
类:

]<?php
class Google_API_translator {
public $opts = array("text" => "", "language_pair" => "en|it");
public $out = "";

function __construct() {}

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://google.com/translate_t?langpair=";
$google_translator_url .= urlencode($this->opts["language_pair"])."&";
$google_translator_url .= "text=".urlencode($this->opts["text"]);
$gphtml = $this->getPage(array("url" => $google_translator_url));
preg_match('/(.*?)</div>/', $gphtml, $out);
$this->out = utf8_encode($out[0]);
return $this->out;
}

function getPage($opts) {
$html = "";
if($opts["url"] != "") {
$ch = curl_init($opts["url"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$html = curl_exec($ch);
if(curl_errno($ch)) {
$html = "";
}
curl_close ($ch);
}
return $html;
}
}
?>


例子:
]<?php
$g = new Google_API_translator();
$g->setOpts(array("text" => "ciao", "language_pair" => "it|en"));
$g->translate();
echo $g->out;
?>

[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  google php api pair function url