21,893
社区成员
发帖
与我相关
我的任务
分享
$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
(
[0] => Chinese
[1] => facebook
[2] => English
)
[key] => 中文
)
[1] => Array
(
[value] => Array
(
[0] => Chinese school
[1] => Schools-Chinese
[2] => Chinese Language School
)
[key] => 中文学校
)
[2] => Array
(
[value] => Array
(
[0] => fbook
[1] => facebook
[2] => face
)
[key] => 中文登入
)
)
)
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");
public 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);
$jsonValue = json_decode ( $value, true );
//翻译成功
$errorCode = $jsonValue["erroeCode"];
$trans = '';
if (isset($errorCode)) {
switch ($errorCode) {
case 0:
$trans = $jsonValue["translation"]['0'];
break;
case 20:
$trans = '要翻译的文本过长';
break;
case 30:
$trans = '无法进行有效的翻译';
break;
case 40:
$trans = '不支持的语言类型';
break;
case 50:
$trans = '无效的key';
break;
default:
$trans = '出现异常';
break;
}
}
return $trans;
}
}