PHP public platform development-translation function development. [PHP public platform development series] 01. configure interface 02. public platform sample code analysis 03. subscribe processing 04. simple reply function development 05. weather forecast function [PHP public platform development series] 01. configuration interface
02. public platform sample code analysis
03. subscribe processing
04. simple reply function development
05. Development of the weather forecast function
06. development of translation functions
I. INTRODUCTION
The previous article introduced the development of the weather forecast function of the public platform and realized the first practical application of the public platform. in the next article, we will briefly develop the translation function, for your reference.
II. train of thought analysis
Similar to the weather query idea in the previous article, you must first judge the messages sent by the user to determine whether the messages contain the "translation" keyword. if so, extract the content to be translated, then, call the Open Translation API on the network for translation.
III. Translation API analysis
There are many translation APIs on the network, so you can choose based on your needs. Here we choose the Youdao translation API and Baidu translation API, which are widely used and have good translation functions. next we will analyze the information about these two APIs.
3.1 Youdao translation API
3.1.1 API address: http://fanyi.youdao.com/openapi
Note:The API interface provided by Youdao is incorrectly returned in the following json data format during the test. go to the internet to check the information. the correct translation address is http://fanyi.youdao.com/fanyiapi.
3.1.2 key application
Fill in relevant information as required, which will be used below, so please fill in carefully and truthfully.
After the application is completed, the API key and keyfrom will be generated below, which will be used when using the API.
3.1.3 API usage example
3.1.4 data format
A. xml format
Http://fanyi.youdao.com/openapi.do? Keyfrom = orchid & key = 1008797533 & type = data & doctype = xml & version = 1.1 & q = Here is the Youdao translation API
0
这里是有道翻译API
Here is the youdao translation API
B. json format
Http://fanyi.youdao.com/openapi.do? Keyfrom = orchid & key = 1008797533 & type = data & doctype = json & version = 1.1 & q = translation
{"ErrorCode": 0 "query": "translation", "translation": ["translation"], // Youdao translation "basic ": {// Youdao dictionary-basic dictionary "phonetic": "f weight n y weight", "explains": ["translate", "interpret"]}, "web ": [// Youdao dictionary-network meaning {"key": "translation", "value": ["translator", "translation", "translate", "Interpreter"]}, {...}]}
3.2 Baidu translation API
3.2.1 API address: http://openapi.baidu.com/public/2.0/bmt/translate
3.2.2 obtain the api key
The developer registers the authorized API key on the Baidu connection platform. for details, see: http://developer.baidu.com/wiki/index.php? Title = % E5 % B8 % AE % E5 % 8A % A9 % E6 % 96% E6 % A1 % A3 % E9 % A6 % 87% E9 % A1 % B5/% E7 % BD % 91% E7 % AB % 99% E6 % 8E % A5 % E5 % 85% A5/% E5 % 85% A5 % E9 % 97% A8 % E6 % 8C % 87% E5 % 8D % 97
3.2.3 API usage example
3.2.4 data format
The data format of Baidu translation API response is the UTF-8 encoded PHP array corresponding to the standard JSON string.
{ “from”:”zh”, “to”:”en”, “trans_result”:[]}
Trans_result is an array, where every {} is a paragraph. The structure is as follows:
trans_result: [{},{},{}]
The paragraph result is one of the trans_result arrays:
{“src”:””,“dst”:””}
Description of paragraph results:
Form after json_decode:
{"From": "en", "to": "zh", "trans_result": [{"src": "today", "dst ": "Today"}]}
IV. keyword judgment and content to be translated to be read
The message to be translated is in the format of "translation + content to be translated". Therefore, the first two words are intercepted to determine whether the message is a "translation" keyword.
Use the php function mb_substr () to intercept the function. the usage of this function has been discussed in the previous article.
$ Str_trans = mb_substr ($ keyword, "UTF-8 ");
Start from the beginning of the message, intercept two characters, and then judge whether it is a "translation" keyword.
$ Str_valid = mb_substr ($ keyword, 0,-2, "UTF-8 ");
Determine whether to enter only the word "translation". if the input is blank, the entered message is incorrect.
Next, extract the content to be translated:
$ Word = mb_substr ($ keyword, 2,220, "UTF-8 ");
The content to be translated is captured starting with 3rd characters and then 202 characters.
Then, call the function for translation.
// Call Youdao dictionary $ contentStr = $ this-> youdaoDic ($ word); // call Baidu Dictionary $ contentStr = $ this-> baiduDic ($ word );
V. implementation
5.1 Youdao translation API
Data interface:
Http://fanyi.youdao.com/openapi.do? Keyfrom = <keyfrom> & key =
& Amp; type = data & doctype =
& Version = 1.1 & q = text to be translated
Replace the preceding keyfrom and key with the requested content, select doctype, and enter the text to be translated. then, you can call the Youdao translation API for translation.
Youdao translation provides three data formats: xml and json.
5.1.1 xml format
The key code is as follows:
Public function youdaoDic ($ word) {$ keyfrom = "orchid"; // content of the website name filled in when you apply for an APIKEY $ apikey = "YourApiKey "; // Apply for APIKEY from Youdao // The xml format $ url_youdao = 'http: // fanyi.youdao.com/fanyiapi.do? Keyfrom = '. $ keyfrom. '& key = '. $ apikey. '& type = data & doctype = xml & version = 1.1 & q = '. $ word; $ xmlStyle = simplexml_load_file ($ url_youdao); $ errorCode = $ xmlStyle-> errorCode; $ paras = $ xmlStyle-> translation-> paragraph; if ($ errorCode = 0) {return $ paras;} else {return "no valid translation allowed ";}}
Note:
$ XmlStyle = simplexml_load_file ($ url_youdao); // PHP function to load the XML file into the object.
$ ErrorCode = $ xmlStyle-> errorCode; // get the error code
$ Paras = $ xmlStyle-> translation-> paragraph; // get the translation content
5.1.2 json format
The key code is as follows:
Public function youdaoDic ($ word) {$ keyfrom = "orchid"; // content of the website name filled in when you apply for an APIKEY $ apikey = "YourApiKey "; // Apply for APIKEY from Youdao // Youdao in json format $ url_youdao =' http://fanyi.youdao.com/fanyiapi.do?keyfrom= '. $ Keyfrom. '& key = '. $ apikey. '& type = data & doctype = json & version = 1.1 & q = '. $ word; $ jsonStyle = file_get_contents ($ url_youdao); $ result = json_decode ($ jsonStyle, true); $ errorCode = $ result ['errorcode']; $ trans = ''; if (isset ($ errorCode) {switch ($ errorCode) {case 0: $ trans = $ result ['translation'] ['0']; break; case 20: $ trans = 'long text to be translated '; break; case 30: $ trans = 'no valid translations allowed'; break; case 40: $ trans = 'unsupported language type'; break; case 50: $ trans = 'invalid key'; break; default: $ trans = 'exception '; break;} return $ trans ;}
Note:
$ JsonStyle = file_get_contents ($ url_youdao); // read the entire file into a string.
$ Result = json_decode ($ jsonStyle, true); // Encode a JSON string
$ ErrorCode = $ result ['errorcode']; // get the error code
$ Trans = $ result ['translation'] ['0']; // Obtain the translation result
5.2 Baidu translation API
API provides UTF-8 encoded PHP array corresponding to the standard JSON string, and provides medium-> English, medium-> Japanese, English-> in, japanese-> Four types of translation, one more than Youdao translation.
The key code is as follows:
// Baidu translation public function baiduDic ($ word, $ from = "auto", $ to = "auto ") {// urlencode the text to be translated first $ word_code = urlencode ($ word); // The registered API Key $ appid = "YourApiKey "; // Generate the url get address for the translation API $ baidu_url =" http://openapi.baidu.com/public/2.0/bmt/translate?client_id= ". $ Appid. "& q = ". $ word_code. "& from = ". $ from. "& to = ". $ to; $ text = json_decode ($ this-> language_text ($ baidu_url); $ text = $ text-> trans_result; return $ text [0]-> dst ;} // Obtain the content printed by the target URL. public function extends age_text ($ url) {if (! Function_exists ('File _ get_contents ') {$ file_contents = file_get_contents ($ url);} else {// initialize a cURL object $ ch = curl_init (); $ timeout = 5; // Set the URL curl_setopt ($ ch, CURLOPT_URL, $ url) to be crawled; // Set the cURL parameter to ensure that the result is saved to the string or output to the screen curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); // The waiting time before the connection is initiated. if it is set to 0, it will be infinitely waiting for curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout); // run cURL, request webpage $ file_contents = curl_exec ($ ch); // close URL request curl_close ($ ch);} return $ file_contents ;}
Note:
There are two functions: baiduDic () and language_text ().
BaiduDic () function:
$ Word_code = urlencode ($ word); // urlencode the text to be translated first
$ Text = json_decode ($ this-> language_text ($ baidu_url); // call the language_text () function to obtain the content printed by the target URL and encode the string in JSON format.
$ Text = $ text-> trans_result; // get the translation result array
Return $ text [0]-> dst; // Obtain the dst result of the first array.
Language_text () function:
Determine whether the file_get_contents () function exists. If yes, use this function to obtain the URL content. If no, use the cURL tool to obtain the URL content. For more information, see the code.
VI. test
Xml format:
Json format:
Baidu translation:
01. configuration interface 02. public platform sample code analysis 03. subscribe processing 04. simple reply function development 05. weather forecast function...