search
HomeBackend DevelopmentPHP TutorialPHP WeChat public platform development - translation function development_PHP tutorial

[PHP WeChat public platform development series]

01. Configure WeChat interface
02. Public platform sample code analysis
03. Subscription event (subscribe) processing
04. Development of simple reply function
05. Weather forecast function development
06. Translation function development


1. Introduction

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 refer to.

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 open translation API on the Internet. Related translations.

3. Translation API Analysis

There are many translation APIs on the Internet, and you can choose one 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=xml&version=1.1&q=Here is Youdao Translation API

PHP WeChat public platform development - translation function development_PHP tutorial
<?xml version="1.0" encoding="UTF-8"?>
<youdao-fanyi>
    <errorCode>0</errorCode>
    <!-- 有道翻译 -->
    <query><![CDATA[这里是有道翻译API]]></query>
    <translation>
        <paragraph><![CDATA[Here is the youdao translation API]]></paragraph>
    </translation>
</youdao-fanyi>
PHP WeChat public platform development - translation function development_PHP tutorial

b. json format

http://fanyi.youdao.com/openapi.do?keyfrom=orchid&key=1008797533&type=data&doctype=json&version=1.1&q=Translation

PHP WeChat public platform development - translation function development_PHP tutorial
{
    "errorCode":0
    "query":"翻译",
    "translation":["translation"], // 有道翻译
    "basic":{ // 有道词典-基本词典
        "phonetic":"fān y&igrave;",
        "explains":[
            "translate",
            "interpret"
        ]
    },
    "web":[ // 有道词典-网络释义
        {
            "key":"翻译",
            "value":["translator","translation","translate","Interpreter"]
        },
        {...}
    ]
}
PHP WeChat public platform development - translation function development_PHP tutorial

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

3.2.4 Data format

The data format of Baidu Translation API response is a standard JSON string corresponding to a UTF-8 encoded PHP array.

{
    &ldquo;from&rdquo;:&rdquo;zh&rdquo;,
    &ldquo;to&rdquo;:&rdquo;en&rdquo;,
    &ldquo;trans_result&rdquo;:[]
}

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

trans_result: [
{},
{},
{}
]

The paragraph result is an item in the trans_result array:

{
&ldquo;src&rdquo;:&rdquo;&rdquo;,
&ldquo;dst&rdquo;:&rdquo;&rdquo;
}

Paragraph result description:

The form after json_decode:

PHP WeChat public platform development - translation function development_PHP tutorial
{
    "from": "en",
    "to": "zh",
    "trans_result": [
        {
            "src": "today",
            "dst": "今天"
        }
    ]
}
PHP WeChat public platform development - translation function development_PHP tutorial

4. Keyword judgment and reading of content to be translated

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.

$str_trans = mb_substr($keyword,0,2,"UTF-8");

Start intercepting from the beginning of the message, intercept two characters, and then determine whether it is the "translation" keyword.

$str_valid = mb_substr($keyword,0,-2,"UTF-8");

Determine whether to enter only the word "translation". If there is no content to be translated, the entered message will not be correct.

Next, extract the content to be translated:

$word = mb_substr($keyword,2,220,"UTF-8");

从消息的开头第3个字符开始截取,截取202个字符,截取出来的即为待翻译内容。

接着调用函数进行翻译。

//调用有道词典
$contentStr = $this->youdaoDic($word);
//调用百度词典
$contentStr = $this->baiduDic($word);

五、具体实现

5.1 有道翻译API

数据接口:

http://fanyi.youdao.com/openapi.do?keyfrom=<keyfrom>&key=<key>&type=data&doctype=<doctype>&version=1.1&q=要翻译的文本

将上面的keyfrom 和key换成上面申请的内容,然后选择doctype,再输入要翻译的文本,就可以调用有道翻译API 进行翻译了。

有道翻译提供了三种数据格式,这里我们只讲解两种,即xml 和json。

5.1.1 xml 格式

关键代码如下:

PHP WeChat public platform development - translation function development_PHP tutorial
public function youdaoDic($word){

        $keyfrom = "orchid";    //申请APIKEY 时所填表的网站名称的内容
        $apikey = "YourApiKey";  //从有道申请的APIKEY
        
        //有道翻译-xml格式
        $url_youdao = &#39;http://fanyi.youdao.com/fanyiapi.do?keyfrom=&#39;.$keyfrom.&#39;&key=&#39;.$apikey.&#39;&type=data&doctype=xml&version=1.1&q=&#39;.$word;
        
        $xmlStyle = simplexml_load_file($url_youdao);
        
        $errorCode = $xmlStyle->errorCode;

        $paras = $xmlStyle->translation->paragraph;

        if($errorCode == 0){
            return $paras;
        }else{
            return "无法进行有效的翻译";
        }
}
PHP WeChat public platform development - translation function development_PHP tutorial

说明:

$xmlStyle = simplexml_load_file($url_youdao);  // PHP 函数,将XML 文档载入对象中。

$errorCode = $xmlStyle->errorCode;  // 获取错误码

$paras = $xmlStyle->translation->paragraph;  // 获取翻译内容

5.1.2 json 格式

关键代码如下:

PHP WeChat public platform development - translation function development_PHP tutorial
    public function youdaoDic($word){

        $keyfrom = "orchid";    //申请APIKEY时所填表的网站名称的内容
        $apikey = "YourApiKey";  //从有道申请的APIKEY
        
        //有道翻译-json格式
        $url_youdao = &#39;http://fanyi.youdao.com/fanyiapi.do?keyfrom=&#39;.$keyfrom.&#39;&key=&#39;.$apikey.&#39;&type=data&doctype=json&version=1.1&q=&#39;.$word;
        
        $jsonStyle = file_get_contents($url_youdao);

        $result = json_decode($jsonStyle,true);
        
        $errorCode = $result[&#39;errorCode&#39;];
        
        $trans = &#39;&#39;;

        if(isset($errorCode)){

            switch ($errorCode){
                case 0:
                    $trans = $result[&#39;translation&#39;][&#39;0&#39;];
                    break;
                case 20:
                    $trans = &#39;要翻译的文本过长&#39;;
                    break;
                case 30:
                    $trans = &#39;无法进行有效的翻译&#39;;
                    break;
                case 40:
                    $trans = &#39;不支持的语言类型&#39;;
                    break;
                case 50:
                    $trans = &#39;无效的key&#39;;
                    break;
                default:
                    $trans = &#39;出现异常&#39;;
                    break;
            }
        }
        return $trans;
        
    }
PHP WeChat public platform development - translation function development_PHP tutorial

说明:

$jsonStyle = file_get_contents($url_youdao);  // 把整个文件读入一个字符串中

$result = json_decode($jsonStyle,true);  // 对JSON 格式的字符串进行编码

$errorCode = $result['errorCode'];  // 获取错误码

$trans = $result['translation']['0'];  // 获取翻译结果

5.2 百度翻译API

百度翻译API提供UTF-8编码的PHP数组对应的标准JSON字符串,而且提供了 中->英,中->日,英->中,日->中 四种互译,比有道翻译多了一种。

关键代码如下:

PHP WeChat public platform development - translation function development_PHP tutorial
    //百度翻译
    public function baiduDic($word,$from="auto",$to="auto"){
        
        //首先对要翻译的文字进行 urlencode 处理
        $word_code=urlencode($word);
        
        //注册的API Key
        $appid="YourApiKey";
        
        //生成翻译API的URL GET地址
        $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;
    }
        
    //百度翻译-获取目标URL所打印的内容
    public function language_text($url){

        if(!function_exists(&#39;file_get_contents&#39;)){

            $file_contents = file_get_contents($url);

        }else{
                
            //初始化一个cURL对象
            $ch = curl_init();

            $timeout = 5;

            //设置需要抓取的URL
            curl_setopt ($ch, CURLOPT_URL, $url);

            //设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上
            curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

            //在发起连接前等待的时间,如果设置为0,则无限等待
            curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

            //运行cURL,请求网页
            $file_contents = curl_exec($ch);

            //关闭URL请求
            curl_close($ch);
        }

        return $file_contents;
    }
PHP WeChat public platform development - translation function development_PHP tutorial

说明:

这里包含了两个函数,baiduDic() 和 language_text()。

baiduDic() 函数:

$word_code=urlencode($word);  // 首先对要翻译的文字进行 urlencode 处理

$text=json_decode($this->language_text($baidu_url));  // 调用language_text() 函数获取目标URL所打印的内容,然后对JSON 格式的字符串进行编码

$text = $text->trans_result;  //获取翻译结果数组

return $text[0]->dst;  //取第一个数组的dst 结果。

language_text() 函数:

判断file_get_contents() 函数是否存在,如果存在,则使用该函数获取URL内容;如果不存在,则使用cURL 工具获取URL内容。具体参见代码。

六、测试

有道翻译-xml 格式:

有道翻译-json 格式:

百度翻译:

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/739142.htmlTechArticle【PHP微信公众平台开发系列】 01.配置微信接口 02.公众平台示例代码分析 03.订阅事件(subscribe)处理 04.简单回复功能开发 05.天气预报功能...
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
Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Give an example of how to store a user's name in a PHP session.Give an example of how to store a user's name in a PHP session.Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools