【问题标题】:How to decode Google translate response with php?如何用 php 解码谷歌翻译响应?
【发布时间】:2011-09-29 18:10:08
【问题描述】:

当您 GET 或 POST 时: "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 风格)

【问题讨论】:

  • 你试过json_decode吗?

标签: php json google-translate


【解决方案1】:
 //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

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

【讨论】:

    【解决方案2】:

    要让api返回JSON更改参数

    client=t
    

    client=p
    

    【讨论】:

    • 客户端参数是什么意思?有文件吗?谢谢!
    • 我不完全确定,这是未记录的功能。
    • 您的回答对我帮助很大,我在下面附上了完整的答案。谢谢
    【解决方案3】:

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

    【讨论】:

    • 你应该首先在google url的pars中使用client=p来启用json_decode fun
    猜你喜欢
    • 2019-02-01
    • 1970-01-01
    • 2011-06-06
    • 2012-01-26
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    相关资源
    最近更新 更多