开发者

How to decode Google translate response with php?

When you GET or POST this: "h开发者_C百科ttp://translate.google.com/translate_a/t","client=t&sl=auto&tl=".urlencode($lang)."&text=".urlencode($text)

the response looks like this:

[[["автомобил","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]

How to decode that? (maybe in json_decode style)


To get the api to return JSON change the parameter

client=t

to

client=p


 //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 and do described on screenshot

//you should have firebug extension installed on your browser

How to decode Google translate response with php?

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


Try using PHP's json_decode function to convert that data to native PHP data types.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜