用fsockopen抓取谷歌翻译得到乱码,请高手解码

life169 2016-08-03 03:20:58
据说原来谷歌翻译是有免费的api可用的,后来谷歌翻译改收费了。
我用fsockopen模拟提交 汉译英
谷歌翻译是以get方式提交的。
为了避免走弯路,我先用抓包工具,走了一下流程,然后用fsockopen完全模拟浏览器提交翻译,然而获得的却是乱码

header("Content-type: text/html; charset=utf-8");
$fp = fsockopen("translate.google.cn", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: translate.google.cn\r\n";
$out .= "User-Agent: ".$_SERVER['HTTP_USER_AGENT']."\r\n";
$out .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
$out .= "Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3\r\n";
$out .= "Accept-Encoding: gzip, deflate\r\n";
$out .= "Connection: Close\r\n\r\n";

fwrite($fp, $out);
$conts = '' ;
while (!feof($fp)) {
//echo fgets($fp, 128);
$tmpstr = fgets($fp, 128);
$conts .= $tmpstr ;
}
fclose($fp);

if(preg_match("#Set-Cookie:\s+(.*)#i", $conts, $arr)){
$cookies =trim($arr[1]);
}
}

$fp = fsockopen("translate.google.cn", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET /translate_a/single?client=t&sl=zh-CN&tl=en&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&ie=UTF-8&oe=UTF-8&source=btn&ssel=0&tsel=0&kc=0&tk=52351.456511&q=%E4%BD%A0%E4%BB%AC HTTP/1.1\r\n";
$out .= "Host: translate.google.cn\r\n";
$out .= "User-Agent: ".$_SERVER['HTTP_USER_AGENT']."\r\n";
$out .= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
$out .= "Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3\r\n";
$out .= "Accept-Encoding: gzip, deflate\r\n";
$out .= "Referer: http://translate.google.cn/\r\n";
$out .= "Cookie: {$cookies}\r\n";
$out .= "Connection: Close\r\n\r\n";

fwrite($fp, $out);
$conts = '' ;
while (!feof($fp)) {
$tmpstr = fgets($fp, 128);
$conts .= $tmpstr ;
}
fclose($fp);
if(preg_match("#Content-Length:\s+\d+\s+(.*)#is", $conts, $arr)){
$outstr =trim($arr[1]);
echo $outstr ;
}
}

得到的应该类似这样的json字符串:

[[["I am Chinese","我是中国人",,,1],[,,,"Wǒ shì zhōngguó rén"]],,"zh-CN",,,[["我是中国人",32000,[["I am Chinese",1000,true,false],["I am Chinese",1000,true,false]],[[0,5]],"我是中国人",0,0]],0.84064001,,[["zh-CN"],,[0.84064001],["zh-CN"]],,,,,,[["我","是","中国","中","人","国"]]]

但我得到的却是乱码:
乱码内容贴不上来,系统不允许。

请高手解码,万分感谢!
...全文
171 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
life169 2016-08-03
  • 打赏
  • 举报
回复
谢谢;qq_23033339 完全解决了我的问题,结贴,给分。
下雨的声音丶 2016-08-03
  • 打赏
  • 举报
回复
别加$out .= "Accept-Encoding: gzip, deflate\r\n"; 这个,因为加了这个返回的是压缩后的
life169 2016-08-03
  • 打赏
  • 举报
回复
用 mb_check_encoding 检出不是 utf-8
life169 2016-08-03
  • 打赏
  • 举报
回复
既然是乱码,我就试试转码

$outstr = mb_convert_encoding ($outstr, "utf-8");
//或者
$outstr = mb_convert_encoding ($outstr, "utf-8", "auto");
没有作用,依然是乱码。

21,886

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧