当前位置:Gxlcms > PHP教程 > PHP调用有道词典翻译API实现通译功能及代码

PHP调用有道词典翻译API实现通译功能及代码

时间:2021-07-01 10:21:17 帮助过:26人阅读

PHP调用有道词典翻译API实现翻译功能及代码
PHP调用有道词典翻译API实现翻译功能及代码,其中英文可以翻译,中文不能翻译是什么问题啊?急
http://fanyi.youdao.com/openapi.do?keyfrom=cxvsdffd33&key=1310976914&type=data&doctype=xml&version=1.1&q=中文"
------解决方案--------------------
function getTransContent($url) {
// $url = "http://fanyi.youdao.com/openapi.do?keyfrom=cxvsdffd33&key=1310976914&type=data&doctype=xml&version=1.1&q=" .urlencode($this->keyword);
// echo $url;
// $url = urlencode($url);
$value = file_get_contents($url);// echo $value;


// $ch = curl_init();

// curl_setopt($ch, CURLOPT_URL, $url);

// $html = curl_exec($ch);
$ar = simplexml_load_string($value,'SimpleXMLElement',LIBXML_NOCDATA
------解决方案--------------------
LIBXML_NOBLANKS);
//$jsonValue = json_decode ( $value, true );

$errorCode = $ar->errorCode;echo $errorCode.PHP_EOL;
//翻译成功
// $errorCode = $jsonValue["erroeCode"];
$trans = '';

if (isset($errorCode)) {
switch ($errorCode) {
case 0:
$trans = $ar->translation->paragraph;
break;
case 20:
$trans = '要翻译的文本过长';
break;
case 30:
$trans = '无法进行有效的翻译';
break;
case 40:
$trans = '不支持的语言类型';
break;
case 50:
$trans = '无效的key';
break;
default:
$trans = '出现异常';
break;
}
}
return $trans;
}
$s=urlencode('中文');
echo getTransContent("http://fanyi.youdao.com/openapi.do?keyfrom=cxvsdffd33&key=1310976914&type=data&doctype=xml&version=1.1&q=$s");

------解决方案--------------------
$c = iconv('gbk', 'utf-8', '中文'); //gbk 一定要转成 utf-8
$c = urlencode($c); //必须做 url 编码
$url = "http://fanyi.youdao.com/openapi.do?keyfrom=cxvsdffd33&key=1310976914&type=data&doctype=json&version=1.1&q=$c";
//返回类型 设为 json,这样处理起来方便些
$s = file_get_contents($url);
print_r(json_decode($s, 1));
Array
(
[translation] => Array
(
[0] => Chinese
)

[basic] => Array
(
[phonetic] => zhōng wén
[explains] => Array
(
[0] => [语] Chinese
)

)

[query] => 中文
[errorCode] => 0
[web] => Array
(
[0] => Array
(
[value] => Array

人气教程排行