Google翻译接口(PHP API)

PHP 林涛 6981℃ 0评论

废话不讲了,直接上代码:

class Google_API_translator {
public $url = “http://translate.google.com/translate_t”;
public $text = “”;//翻译文本
public $out = “”; //翻译输出

function setText($text){
$this->text = $text;
}

function translate() {
$this->out = “”;

$gphtml = $this->postPage($this->url, $this->text);

//提取翻译结果
$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 – 界面语言,此处无用。
*langpair – src lang to dest lang
*ie – urlencode的编码方式?
*text – 要翻译的文本
*/
$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(“我爱Java!”);
$g->translate();
echo $g->out;
?>

如需转载请注明: 转载自26点的博客

本文链接地址: Google翻译接口(PHP API)

转载请注明:26点的博客 » Google翻译接口(PHP API)

喜欢 (0)or分享 (0)
0 0 投票数
文章评分
订阅评论
提醒
guest

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据

0 评论
内联反馈
查看所有评论
0
希望看到您的想法,请您发表评论x