Home Backend Development PHP Tutorial WeChat public platform development (6) Translation function development_PHP tutorial

WeChat public platform development (6) Translation function development_PHP tutorial

Jul 20, 2016 am 11:14 AM
superior Function weather forecast accomplish platform develop WeChat article of translate

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>
Copy after login

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&igrave;",
        "explains":[
            "translate",
            "interpret"
        ]
    },
    "web":[ // 有道词典-网络释义
        {
            "key":"翻译",
            "value":["translator","translation","translate","Interpreter"]
        },
        {...}
    ]
}</span>
Copy after login

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 {
    &ldquo;from&rdquo;:&rdquo;zh&rdquo;,
    &ldquo;to&rdquo;:&rdquo;en&rdquo;,
    &ldquo;trans_result&rdquo;:[]
}</span>
Copy after login

trans_result is an array, each {} is a paragraph, and the structure is as follows:

<span trans_result: [
{},
{},
{}
]</span>
Copy after login

The paragraph result is an item in the trans_result array:

<span {
&ldquo;src&rdquo;:&rdquo;&rdquo;,
&ldquo;dst&rdquo;:&rdquo;&rdquo;
}</span>
Copy after login

Paragraph result description:

Form after json_decode:

<span {
    "from": "en",
    "to": "zh",
    "trans_result": [
        {
            "src": "today",
            "dst": "今天"
        }
    ]
}</span>
Copy after login

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>);
Copy after login

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>=要翻译的文本
Copy after login

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>
Copy after login

说明:

$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>
Copy after login

说明:

把整个文件读入一个字符串中

$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>
Copy after login

说明:

baiduDic() 函数:

language_text() 函数:

有道翻译-xml 格式:

有道翻译-json 格式:

百度翻译:

注意:该翻译功能放在SAE上能够正常运行,但在BAE上运行不成功,各位有兴趣自行测试一下。

请到QQ群213260412共享里下载使用。

请关注 卓锦苏州 微信公众帐号,卓锦苏州 基于SAE 平台开发,针对于主流的微信功能进行开发测试。

您可以关注 卓锦苏州 公众帐号进行功能测试,以及获取新的应用开发。

1. 登录微信客户端,朋友们 -> 添加朋友 -> 搜号码 -> zhuojinsz,查找并关注。

2. 扫描二维码:

卓锦苏州功能列表。

 


We Believe, Great People Share Knowledge...

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440249.htmlTechArticleThe previous article introduced the development of the weather forecast function of the WeChat public platform, realizing the first WeChat public platform Practical application, in the next article, we will translate WeChat...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

deepseek image generation tutorial deepseek image generation tutorial Feb 19, 2025 pm 04:15 PM

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI ​​Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

gateio Chinese official website gate.io trading platform website gateio Chinese official website gate.io trading platform website Feb 21, 2025 pm 03:06 PM

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

List of handling fees for okx trading platform List of handling fees for okx trading platform Feb 15, 2025 pm 03:09 PM

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

gateio exchange app old version gateio exchange app old version download channel gateio exchange app old version gateio exchange app old version download channel Mar 04, 2025 pm 11:36 PM

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Mar 04, 2025 pm 04:51 PM

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

How to copy Xiaohongshu copywriting. Graphical tutorial on how to copy Xiaohongshu copywriting. How to copy Xiaohongshu copywriting. Graphical tutorial on how to copy Xiaohongshu copywriting. Jan 16, 2025 pm 04:03 PM

Learn to easily copy Xiaohongshu copywriting! This tutorial teaches you step by step how to quickly copy Xiaohongshu video copy, saying goodbye to tedious steps. Open the Xiaohongshu APP, find the video you like, and click on the [Copywriting] area below the video. Long press the copy text and select the [Extract Text] function from the pop-up options. The system will automatically extract the text, click the [Copy] button in the lower left corner. Open WeChat or other applications, such as Moments, long press the input box, and select [Paste]. Click Send to complete the copy. It's that simple!

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

See all articles