Google翻译接口(PHP API)

/* Google翻译PHP接口

 * 官成文 2009-03-28

 * http://blog.csdn.net/aprin/

 * 注意:如果翻译文本为UTF-8编码,则要删去mb_convert_encoding函数

 */

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(“我爱php100!”);

 $g->translate();

 echo $g->out;

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值