PHP WeChat public platform development-translation function development

Source: Internet
Author: User

[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

<? Xml version = "1.0" encoding = "UTF-8"?> <Youdao-fanyi> <errorCode> 0 </errorCode> <! -- Youdao Translation --> <query> <! [CDATA [API]> </query> <translation> <paragraph> <! [CDATA [Here is the youdao translation API]> </paragraph> </translation> </youdao-fanyi>

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 = <key> & type = data & doctype = <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 // $ 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 translation api url get address $ 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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.