Maison >développement back-end >tutoriel php >PHP调用有道词典翻译API实现通译功能及代码
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) {<br /> // $url = "http://fanyi.youdao.com/openapi.do?keyfrom=cxvsdffd33&key=1310976914&type=data&doctype=xml&version=1.1&q=" .urlencode($this->keyword);<br /> // echo $url;<br /> // $url = urlencode($url);<br /> $value = file_get_contents($url);// echo $value;<br /> <br /><br /> // $ch = curl_init();<br /> <br /> // curl_setopt($ch, CURLOPT_URL, $url);<br /> <br /> // $html = curl_exec($ch);<br /> $ar = simplexml_load_string($value,'SimpleXMLElement',LIBXML_NOCDATA <br><font color='#FF8000'>------解决方案--------------------</font><br> LIBXML_NOBLANKS);<br /> //$jsonValue = json_decode ( $value, true );<br /> <br /> $errorCode = $ar->errorCode;echo $errorCode.PHP_EOL;<br /> //翻译成功<br /> // $errorCode = $jsonValue["erroeCode"];<br /> $trans = '';<br /> <br /> if (isset($errorCode)) {<br /> switch ($errorCode) {<br /> case 0:<br /> $trans = $ar->translation->paragraph;<br /> break;<br /> case 20:<br /> $trans = '要翻译的文本过长';<br /> break;<br /> case 30:<br /> $trans = '无法进行有效的翻译';<br /> break;<br /> case 40:<br /> $trans = '不支持的语言类型';<br /> break;<br /> case 50:<br /> $trans = '无效的key';<br /> break;<br /> default:<br /> $trans = '出现异常';<br /> break; <br /> }<br /> }<br /> return $trans;<br /> }<br />$s=urlencode('中文');<br />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<br />$c = urlencode($c); //必须做 url 编码<br />$url = "http://fanyi.youdao.com/openapi.do?keyfrom=cxvsdffd33&key=1310976914&type=data&doctype=json&version=1.1&q=$c";<br />//返回类型 设为 json,这样处理起来方便些<br />$s = file_get_contents($url);<br />print_r(json_decode($s, 1));<br />
Array<br>(<br> [translation] => Array<br> (<br> [0] => Chinese<br> )<br><br> [basic] => Array<br> (<br> [phonetic] => zhōng wén<br> [explains] => Array<br> (<br> [0] => [语] Chinese<br> )<br><br> )<br><br> [query] => 中文<br> [errorCode] => 0<br> [web] => Array<br> (<br> [0] => Array<br> (<br> [value] => Array<div class="clear"> </div>