欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP Google的translate API代码

程序员文章站 2022-05-14 12:54:44
新建一个ansi的php文件,然后创建一个类: 复制代码 代码如下:header("content-type: text/html; charset=utf-8"); cl...
新建一个ansi的php文件,然后创建一个类:
复制代码 代码如下:

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

使用的时候
复制代码 代码如下:

$g = new google_api_translator();
$g->setopts(array("text" => "cjjer是天才", "language_pair" => "zh-cn|en"));
$g->translate();
echo $g->out;
?>

这样就可以了,输出:cjjer is genius
php的就这里,参见了部分同学的部分代码。具体忘了。
这段代码不好。。。但可以用,懒得管啦。。