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

WBOY
WBOYOriginal
2016-07-20 11:14:541392browse

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&igrave;",
        "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 {
    &ldquo;from&rdquo;:&rdquo;zh&rdquo;,
    &ldquo;to&rdquo;:&rdquo;en&rdquo;,
    &ldquo;trans_result&rdquo;:[]
}</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 {
&ldquo;src&rdquo;:&rdquo;&rdquo;,
&ldquo;dst&rdquo;:&rdquo;&rdquo;
}</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() 函数:

有道翻译-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:
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