如何解码谷歌翻译响应与PHP?

时间:2011-07-06 15:35:13

标签: php json google-translate

当您获取或发布此信息时: "http://translate.google.com/translate_a/t","client=t&sl=auto&tl=".urlencode($lang)."&text=".urlencode($text)

响应如下:

[[["автомобил","car","avtomobil",""]],,"en",,[["автомобил",[5],1,0,1000,0,1,0]],[["car",5,[["автомобил",1000,1,0],["автомобилот",0,1,0],["автомобили",0,1,0],["кола",0,1,0],["возило",0,1,0]],[[0,3]],"car"]],,,[["en","fr"]],30]

如何解码? (也许是json_decode风格)

3 个答案:

答案 0 :(得分:9)

要让api返回JSON,请更改参数

client=t

client=p

答案 1 :(得分:2)

 //this will translate from en to ar -- you can change it for your needs
 function translate_word($en){
    $file_content = file_get_contents('http://translate.google.com/translate_a/t?client=p&sl=auto&tl=ar&hl=en&sc=2&ie=UTF-8&oe=UTF-8&uptl=ar&oc=1&prev=conf&psl=auto&ptl=en&otf=1&it=sel.8936&ssel=0&tsel=3&q='.str_replace(" ","%20",$en));
    $obj = json_decode($file_content);
    if(!empty($obj->sentences[0]->trans)){
        return $obj->sentences[0]->trans;
    }else{
        return $en;
    }
}
//how to use
echo translate_word("test translation process");
//if you do not know short codes for your language you can just open 

translate.google.com并在屏幕截图中进行了描述

//you should have firebug extension installed on your browser

enter image description here

//if the answer was usefull please do not forget to vote up! thanks.

答案 2 :(得分:0)

尝试使用PHP的json_decode function将该数据转换为本机PHP数据类型。