When doing some Web sites occasionally encounter the need for Chinese and English translation of the part, perhaps to provide users with the function of online translation, may also be the user input a whole paragraph of text to translate. Little Dragon recently encountered such a thing, docking between Chinese and foreign users of the communication, in order to the language is not so smooth users to provide a small help, embedded in the site of automatic translation functions, simplifying the user copy sticky, and then open the steps of Baidu translation.
Dragons use the Youdao API provided, the ordinary user can be used for free. Youdao provides a Web page module of the call method and data interface type, the Web module will be relatively simple, in their official online copy of the code written into the HTML is good, here simply expand the following data interface type calls.
First of all, we need a key, Baidu API has been a friend to this should be completely unfamiliar. Application address: http://ai.youdao.com/, after registration can apply.
The API provided by Youdao is simple:
Http://fanyi.youdao.com/openapi.do? keyfrom=<keyfrom>&key=<key>&type=data&doctype=<doctype>& version=1.1&q= The text to be translated
A very standard get form of data transmission, want to see the results of a friend can directly apply for key after the link to the browser to copy the address bar, open, you can see the data back, remember that the data type must be UTF8, but also URL transcoding oh.
Dragon to a PHP demo for reference:
functionSimple_translate ($sentence){ $url _sentence=UrlEncode($sentence); $url= "http://fanyi.youdao.com/openapi.do?keyfrom=xinlei&key=759115437&type=data&doctype=json& Version=1.1&q= ".$url _sentence; $str _json=file_get_contents($url); if($str _json){ $info= Json_decode ($str _json); $translation=$info-translation; $result _sentence=$translation[0]; }Else{ $result _sentence=$sentence; } return $result _sentence;}
This API has a small drawback, is only 200 characters within the paragraph, more, he Ooxx ~ ~ ~ ~
Our solution, little dragon cut the passage into sentences, and then a sentence, turn over and put together Bai ... The most primitive way, but, very good.
to a stronger version of the demo, it will call the function above
function translate ($string) {if ($string) {$symbol _array = Array (".", "?", "!", ")", "(", "[", "]", "{", "}", ":"); $i = 0; $res Ult = "", while ($i < strlen ($string)) {if (In_array ($string [$i], $symbol _array)) {$s = $string [$i]; $string 1 = substr ($ String, 0, $i), $string 2 = substr ($string, $i + 1), $result = Simple_translate ($string 1). $s. Translate ($string 2); break;} $i + +;} if (! $result) {$result = Simple_translate ($string);} return $result;} Else{return "";}}
According to. , ? ! : () [] {} cut the paragraph, then translate it, and then put it all together.
About website Call online Translator API for translation function