


WeChat public platform development (6) Translation function development_PHP tutorial
The previous article introduced the development of the weather forecast function of the WeChat public platform and realized the first practical application of the WeChat public platform. In the next article, we will briefly develop the WeChat translation function. For readers' reference.
2. Idea analysis
The idea of querying the weather is similar to the previous article. First, the message sent by the user must be judged to determine whether the message contains the "translation" keyword. If it does, extract the content to be translated, and then call the network Use the open translation API for related translations.
There are many translation APIs on the Internet, and you can choose according to your needs. Here we choose Youdao Translation API and Baidu Translation API, which are widely used and have relatively good translation functions. The relevant information of these two APIs will be analyzed below.
3.1 Youdao Translation API
3.1.1 API address: http://fanyi.youdao.com/openapi
Note: The API interface provided by Youdao, during the following test, the json data format returned is incorrect. Check the information online and the address that can be translated correctly is http://fanyi.youdao. com/fanyiapi, pay attention to this.
3.1.2 Apply for key
Fill in the relevant information as required. This information will be used below, so please fill it 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 examples
3.1.4 Data format
a. xml format
http://fanyi.youdao.com/openapi.do?keyfrom=orchid&key=1008797533 &type=data&doctype=&version=1.1&q=This is Youdao Translation API
<span <?</span><span xml version="1.0" encoding="UTF-8"</span><span ?></span> <span <</span><span youdao-fanyi</span><span ></span> <span <</span><span errorCode</span><span ></span>0<span </</span><span errorCode</span><span ></span> <span <!--</span><span 有道翻译 </span><span --></span> <span <</span><span query</span><span ></span><span <![CDATA[</span><span 这里是有道翻译API</span><span ]]></span><span </</span><span query</span><span ></span> <span <</span><span translation</span><span ></span> <span <</span><span paragraph</span><span ></span><span <![CDATA[</span><span Here is the youdao translation API</span><span ]]></span><span </</span><span paragraph</span><span ></span> <span </</span><span translation</span><span ></span> <span </</span><span youdao-fanyi</span><span ></span>
http://fanyi.youdao.com/openapi.do?keyfrom=orchid&key=1008797533&type=data&doctype=&version=1.1&q=translation
<span { "errorCode":0 "query":"翻译", "translation":["translation"], // 有道翻译 "basic":{ // 有道词典-基本词典 "phonetic":"fān yì", "explains":[ "translate", "interpret" ] }, "web":[ // 有道词典-网络释义 { "key":"翻译", "value":["translator","translation","translate","Interpreter"] }, {...} ] }</span>
3.2 Baidu Translation API
3.2.1 API address: http://openapi.baidu.com/public/2.0/bmt/translate
3.2.2 Get api key
The authorized API key obtained by developers registered on Baidu Connection Platform. For details, please refer to: http://developer.baidu.com/wiki/index.php?title=%E5%B8%AE%E5 %8A%A9%E6%96%87%E6%A1%A3%E9%A6%96%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 examples
The data format of Baidu Translation API response is a standard JSON string corresponding to a UTF-8 encoded PHP array.
<span { “from”:”zh”, “to”:”en”, “trans_result”:[] }</span>
trans_result is an array, each {} is a paragraph, and the structure is as follows:
<span trans_result: [ {}, {}, {} ]</span>
The paragraph result is an item in the trans_result array:
<span { “src”:””, “dst”:”” }</span>
Paragraph result description:
Form after json_decode:
<span { "from": "en", "to": "zh", "trans_result": [ { "src": "today", "dst": "今天" } ] }</span>
The format of the translation message is "translation + content to be translated", so first intercept the first two words to determine whether they are the "translation" keyword.
Use the PHP function mb_substr() to intercept. The usage of this function has been discussed in the previous article and will not be repeated here.
Start from the beginning of the message, intercept two characters, and then determine whether it is the "translation" keyword.
Determine whether to enter only the word "translation". If you enter this way, there is no content to be translated, and the entered message will not be correct.
The next step is to extract the content to be translated:
Start from the third character at the beginning of the message and intercept 202 characters. The intercepted content is the content to be translated.
Then call the function for translation.
<span //</span><span 调用有道词典</span> <span $contentStr</span> = <span $this</span>->youdaoDic(<span $word</span><span ); </span><span //</span><span 调用百度词典</span> <span $contentStr</span> = <span $this</span>->baiduDic(<span $word</span>);
5.1 Youdao Translation API
Data interface:
http://fanyi.youdao.com/openapi.do?keyfrom=<span <</span><span keyfrom</span><span ></span><span &key</span>=<span <</span><span key</span><span ></span><span &type</span>=data<span &doctype</span>=<span <</span><span doctype</span><span ></span><span &version</span>=1.1<span &q</span>=要翻译的文本
5.1.1 xml 格式
关键代码如下:
<span public</span> <span function</span> youdaoDic(<span $word</span><span ){ </span><span $keyfrom</span> = "orchid"; <span //</span><span 申请APIKEY 时所填表的网站名称的内容</span> <span $apikey</span> = "YourApiKey"; <span //</span><span 从有道申请的APIKEY //有道翻译-xml格式</span> <span $url_youdao</span> = 'http://fanyi.youdao.com/fanyiapi.do?keyfrom='.<span $keyfrom</span>.'&key='.<span $apikey</span>.'&type=data&doctype=xml&version=1.1&q='.<span $word</span><span ; </span><span $xmlStyle</span> = <span simplexml_load_file</span>(<span $url_youdao</span><span ); </span><span $errorCode</span> = <span $xmlStyle</span>-><span errorCode; </span><span $paras</span> = <span $xmlStyle</span>->translation-><span paragraph; </span><span if</span>(<span $errorCode</span> == 0<span ){ </span><span return</span> <span $paras</span><span ; }</span><span else</span><span { </span><span return</span> "无法进行有效的翻译"<span ; }<br />}</span>
说明:
$xmlStyle = simplexml_load_file($url_youdao); // PHP 函数,将XML 文档载入对象中。
$errorCode = $xmlStyle->errorCode; // 获取错误码
$paras = $xmlStyle->translation->paragraph; // 获取翻译内容
5.1.2 json 格式
关键代码如下:
<span public</span> <span function</span> youdaoDic(<span $word</span><span ){ </span><span $keyfrom</span> = "orchid"; <span //</span><span 申请APIKEY时所填表的网站名称的内容</span> <span $apikey</span> = "YourApiKey"; <span //</span><span 从有道申请的APIKEY //有道翻译-json格式</span> <span $url_youdao</span> = 'http://fanyi.youdao.com/fanyiapi.do?keyfrom='.<span $keyfrom</span>.'&key='.<span $apikey</span>.'&type=data&doctype=json&version=1.1&q='.<span $word</span><span ; </span><span $jsonStyle</span> = <span file_get_contents</span>(<span $url_youdao</span><span ); </span><span $result</span> = json_decode(<span $jsonStyle</span>,<span true</span><span ); </span><span $errorCode</span> = <span $result</span>['errorCode'<span ]; </span><span $trans</span> = ''<span ; </span><span if</span>(<span isset</span>(<span $errorCode</span><span )){ </span><span switch</span> (<span $errorCode</span><span ){ </span><span case</span> 0: <span $trans</span> = <span $result</span>['translation']['0'<span ]; </span><span break</span><span ; </span><span case</span> 20: <span $trans</span> = '要翻译的文本过长'<span ; </span><span break</span><span ; </span><span case</span> 30: <span $trans</span> = '无法进行有效的翻译'<span ; </span><span break</span><span ; </span><span case</span> 40: <span $trans</span> = '不支持的语言类型'<span ; </span><span break</span><span ; </span><span case</span> 50: <span $trans</span> = '无效的key'<span ; </span><span break</span><span ; </span><span default</span>: <span $trans</span> = '出现异常'<span ; </span><span break</span><span ; } } </span><span return</span> <span $trans</span><span ; }</span>
说明:
把整个文件读入一个字符串中
$result = json_decode($jsonStyle,true); // 对JSON 格式的字符串进行编码
$errorCode = $result['errorCode']; // 获取错误码
$trans = $result['translation']['0']; // 获取翻译结果
5.2 百度翻译API
百度翻译API提供UTF-8编码的PHP数组对应的标准JSON字符串,而且提供了 中->英,中->日,英->中,日->中 四种互译,比有道翻译多了一种。
关键代码如下:
<span //</span><span 百度翻译</span> <span public</span> <span function</span> baiduDic(<span $word</span>,<span $from</span>="auto",<span $to</span>="auto"<span ){ </span><span //</span><span 首先对要翻译的文字进行 urlencode 处理</span> <span $word_code</span>=<span urlencode</span>(<span $word</span><span ); </span><span //</span><span 注册的API Key</span> <span $appid</span>="<span YourApiKey</span>"<span ; </span><span //</span><span 生成翻译API的URL GET地址</span> <span $baidu_url</span> = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=".<span $appid</span>."&q=".<span $word_code</span>."&from=".<span $from</span>."&to=".<span $to</span><span ; </span><span $text</span>=json_decode(<span $this</span>->language_text(<span $baidu_url</span><span )); </span><span $text</span> = <span $text</span>-><span trans_result; </span><span return</span> <span $text</span>[0]-><span dst; } </span><span //</span><span 百度翻译-获取目标URL所打印的内容</span> <span public</span> <span function</span> language_text(<span $url</span><span ){ </span><span if</span>(!<span function_exists</span>('file_get_contents'<span )){ </span><span $file_contents</span> = <span file_get_contents</span>(<span $url</span><span ); }</span><span else</span><span { </span><span //</span><span 初始化一个cURL对象</span> <span $ch</span> =<span curl_init(); </span><span $timeout</span> = 5<span ; </span><span //</span><span 设置需要抓取的URL</span> curl_setopt (<span $ch</span>, CURLOPT_URL, <span $url</span><span ); </span><span //</span><span 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上</span> curl_setopt (<span $ch</span>, CURLOPT_RETURNTRANSFER, 1<span ); </span><span //</span><span 在发起连接前等待的时间,如果设置为0,则无限等待</span> curl_setopt (<span $ch</span>, CURLOPT_CONNECTTIMEOUT, <span $timeout</span><span ); </span><span //</span><span 运行cURL,请求网页</span> <span $file_contents</span> = curl_exec(<span $ch</span><span ); </span><span //</span><span 关闭URL请求</span> curl_close(<span $ch</span><span ); } </span><span return</span> <span $file_contents</span><span ; }</span>
说明:
baiduDic() 函数:
language_text($baidu_url)); // 调用language_text() 函数获取目标URL所打印的内容,然后对JSON 格式的字符串进行编码
trans_result; //获取翻译结果数组
dst; //取第一个数组的dst 结果。
language_text() 函数:
有道翻译-xml 格式:
有道翻译-json 格式:
百度翻译:
注意:该翻译功能放在SAE上能够正常运行,但在BAE上运行不成功,各位有兴趣自行测试一下。
请到QQ群213260412共享里下载使用。
请关注 卓锦苏州 微信公众帐号,卓锦苏州 基于SAE 平台开发,针对于主流的微信功能进行开发测试。
您可以关注 卓锦苏州 公众帐号进行功能测试,以及获取新的应用开发。
1. 登录微信客户端,朋友们 -> 添加朋友 -> 搜号码 -> zhuojinsz,查找并关注。
2. 扫描二维码:
卓锦苏州功能列表。
We Believe, Great People Share Knowledge...

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version