php调用百度翻译最新接口代码,调用的方式有少许的变化。具体可以查看百度接口文档。对翻译的值不需要再经过urlencode转化,翻译时需要验证签名。具体的代码如下:
function language($value,$from="auto",$to="auto") { $value_code = $value; //urlencode($value); //首先对要翻译的文字进行 urlencode 处理 $appid = "20151119000000001"; //您注册的API Key $key = "12345678"; //密钥 $salt = rand(1000000000,9999999999); //随机数 $sign = md5($appid.$value_code.$salt.$key); //签名 //生成翻译API的URL GET地址 $languageurl = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=$value_code&appid=$appid&salt=$salt&from=$from&to=$to&sign=$sign"; $text=json_decode(LanguageText($languageurl)); return $text->trans_result; } function LanguageText($url) //获取目标URL所打印的内容 { if(!function_exists('file_get_contents')) { $file_contents = file_get_contents($url); } else { $ch = curl_init(); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5); $file_contents = curl_exec($ch); curl_close($ch); } return $file_contents; } // echo language('中国', 'zh', 'en'); $val = $post['val']; $lan = language($val, 'zh', 'en'); $result = ''; foreach ($lan as $k => $v) { $result .= ucwords($v->dst) ."\n"; } echo json_encode($result); exit();
原文转自 : http://blog.sina.com.cn/s/blog_6ad624380102w2f2.html