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

PHP调用google translate中解决中文返回乱码

2014-08-12 15:35 525 查看
在网上找了段代码获取google翻译结果,不是调用API的。

结果返回结果中中文乱码,并且结果不正确,那么其实发过去的时候就转码有问题。

返回来的就有问题。

$google = $this->curl_file_get_contents("http://translate.google.com/translate_a/t?client=t&text=".$text."&sl=zh_CN&tl=en");


原来的写法返回的中文乱码

解决方法:

加入

$google = $this->curl_file_get_contents("http://translate.google.com/translate_a/t?client=t&ie=UTF-8&oe=UTF-8&text=".$text."&sl=zh_CN&tl=en");
echo $google


返回结果正常

public function curl_file_get_contents($durl){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $durl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回
$r = curl_exec($ch);
curl_close($ch);
return $r;
}

修改后的完整源代码:

<?php

header("Content-Type: text/html; charset=utf-8");

class Google_API_translator {

public $out = "";

function translate( $content, $s, $t ) {

$this->out = "";

$text = urlencode( $content );//要翻译的单词

$google_translator_url = "http://translate.google.com/translate_a/t?client=t&ie=UTF-8&oe=UTF-8&text=".$text."&sl=".$s."&tl=".$t;

$gphtml = $this->postPage(array("url" => $google_translator_url));

$this->out = utf8_encode($gphtml);

return $this->out;
}

function postPage($opts) {

$html = "";

if($opts["url"] != "") {

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $opts["url"]);

$html = curl_exec($ch);

if(curl_errno($ch)) $html = "";
curl_close ($ch);

}

return $html;
}
}

$g = new Google_API_translator();

$g->translate( $_GET['q'], $_GET['s'], $_GET['t']);

?>


访问方法:

http://eqiyu.cn/translator.php?q=%E6%B5%8B%E8%AF%95&s=zh-CN&t=ja


返回:

[[["テスト","测试","Tesuto","Cèshì"]],,"zh-CN",,[["テスト",[1],false,false,999,0,1,0]],[["测试",1,[["テスト",999,false,false],["試験",0,false,false],["検査",0,false,false],["のテスト",0,false,false],["実験",0,false,false]],[[0,2]],"测试"]],,,[["zh-CN"]],13]

http://eqiyu.cn/translator.php?q=%E6%B5%8B%E8%AF%95&s=zh-CN&t=en


返回:

[[["Test","测试","","Cèshì"]],[["noun",["test","examination"],[["test",["测试","试验","试","实验","考试","考验"],[15246],0.29559943],["examination",["考试","检查","试","研究","测试","察看"],[15246],0.00026955179]],"测试",1]],"zh-CN",,[["Test",[1],true,false,542,0,1,0]],[["测试",1,[["Test",542,true,false],["Testing",38,true,false],["Tests",2,true,false],["Tested",0,true,false],["The test",0,true,false]],[[0,2]],"测试"]],,,[],3]


client=t //修改参数,client=j则返回json,貌似只要不是t和空的都返回json
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  乱码 phalcon php utf-8 google