Home WeChat Applet WeChat Development Detailed explanation of the steps for developing the translation function in WeChat

Detailed explanation of the steps for developing the translation function in WeChat

May 13, 2017 pm 02:44 PM

1. Introduction

#The previous article introduced the development of the weather forecast function of the WeChat public platform and implemented the WeChat public platform The first practical application, in the following 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, we must judge the message sent by the user. Whether the message contains the "translation" keyword, if so, extract the content to be translated, and then call the open translationAPI on the Internet for relevant translation.

3. Translation API Analysis

There are many translation APIs on the Internet, you can choose according to your needs . Here we choose Youdao Translation API and Baidu TranslationAPI, which are widely used and have relatively good translation functions. The relevant information of these two APIs is analyzed below.

3.1 Youdao Translation API

3.1.1 API address: fanyi.youdao.com/openapi

Note: The API interface provided by Youdao, during the following test, the data format returned by json is incorrect. Check the information online and the address that can be translated correctly is fanyi.youdao.com/fanyiapi , pay attention to this.

3.1.2 Applicationkey

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 example

##3.1.4 Data format

a. xml Format

fanyi.youdao.com/openapi.do?keyfrom=orchid&key=1008797533 &type=data&doctype=xml&version=1.1&q=This is Youdao Translation API

##

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

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"], // 有道翻译
    "basic":{ // 有道词典-基本词典
        "phonetic":"fān yì",
        "explains":[
            "translate",
            "interpret"
        ]
    },
    "web":[ // 有道词典-网络释义
        {
            "key":"翻译",
            "value":["translator","translation","translate","Interpreter"]
        },
        {...}
    ]
}
Copy after login


3.2 Baidu Translate API

3.2.1 API address: openapi.baidu.com/public/2.0/bmt/translate

3.2 .2 Obtain the api key

The authorized API key obtained by the developer after registering on the 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 UTF-8 encodedPHP array corresponds to the standard JSON

string

.

{
    “from”:”zh”,
    “to”:”en”,
    “trans_result”:[]
}
Copy after login

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


trans_result: [
{},
{},
{}
]
Copy after login

The paragraph result is an item in the trans_result array:


{
“src”:””,
“dst”:””
}
Copy after login

Paragraph result description:


After json_decode The form:

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


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.

使用php函数 mb_substr() 截取,关于该函数的用法上一篇已经讲过,这里不再赘述。

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

从消息的开头开始截取,截取两个字符,然后加以判断是否为 “翻译” 关键字。

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

判断是否只输入“翻译”两字,这样输入,没有待翻译内容,则输入的消息也不正确。

接下来进行待翻译内容提取:

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

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

接着调用函数进行翻译。


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

五、具体实现

5.1 有道翻译API

数据接口:


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

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

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

5.1.1 xml 格式

关键代码如下:


  youdaoDic( = "orchid";    
         = "YourApiKey";  
         = &#39;http://fanyi.youdao.com/fanyiapi.do?keyfrom=&#39;..&#39;&key=&#39;..&#39;&type=data&doctype=xml&version=1.1&q=&#39;. = ( = -> = ->translation->( == 0  "无法进行有效的翻译"
Copy after login

说明:

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

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

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

5.1.2 json 格式

关键代码如下:


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

说明:

$jsonStyle = file_get_contents($url_youdao);  // 把整个文件读入一个字符串中
$result = json_decode($jsonStyle,true);  // 对JSON 格式的字符串进行编码
$errorCode = $result[&#39;errorCode&#39;];  // 获取错误码
$trans = $result[&#39;translation&#39;][&#39;0&#39;];  // 获取翻译结果
Copy after login

5.2 百度翻译API

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

关键代码如下:


    //百度翻译
    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;
    }
Copy after login

说明:

这里包含了两个函数,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 结果。
Copy after login

language_text() 函数:

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

六、测试

有道翻译-xml 格式:

有道翻译-json 格式:

百度翻译:

【相关推荐】

1. 特别推荐“php程序员工具箱”V0.1版本下载

2. 微信公众号平台源码下载

3. 微信投票源码下载

The above is the detailed content of Detailed explanation of the steps for developing the translation function in WeChat. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

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)

How to use wps translation function_How to use wps translation function How to use wps translation function_How to use wps translation function Mar 27, 2024 pm 04:46 PM

1. First, we open wpsoffice on the mobile phone. 2. Then click Apply. 3. Click the image to translate. Method 2 1. First, we open wpsoffice on the mobile phone. 2. Open the document that needs to be translated and click the tool in the lower left corner. 3. Click Review and Translate.

How to get the translation function back in Edge browser if it is missing? How to get the translation function back in Edge browser if it is missing? Mar 13, 2024 pm 08:40 PM

When using a browser to browse the web, you may need to visit some foreign language websites that you cannot understand at all. When you want to open the translation, you find that the built-in translation is missing. Can you still retrieve it? The editor below will share with you how to retrieve the translation function. How to set up translation in Edge browser? First, launch the Edge browser, then find the "More options" icon consisting of three dots in the upper right corner and click on it. 2. After clicking, the menu window of the Edge browser will pop up below. Click in the window to open the "Settings" page. 3. At this time, you will enter the settings page of the Edge browser. You can see the "Language" item in the navigation menu on the left side of the page. Click to switch to this setting.

Where is the translation function of Baidu browser? Where is the translation function of Baidu browser? Feb 27, 2024 pm 02:28 PM

Where is the translation function of Baidu Browser? As a powerful browser, Baidu Mobile Browser has built-in many practical auxiliary functions, such as web page translation function. This function can translate English and other foreign languages ​​on the web page into Chinese, which is extremely useful for users who frequently visit non-Chinese websites. So, how to use the web page translation function in Baidu mobile browser? Next, I will share the detailed method of using the web translation function of mobile Baidu browser, so that friends in need can make better use of this function. How to use the web translation function of mobile Baidu browser 1. First open Baidu browser on your mobile phone and click the "menu" icon composed of three horizontal lines at the bottom of the browser; 2. At this time, the menu window of Baidu browser will pop up at the bottom of the interface. ,we are at

How to use the translation function in excel How to use the translation function in excel Mar 20, 2024 pm 12:40 PM

In daily work, it is inevitable to deal with excel. Sometimes when opening a form, you will encounter several languages. At this time, most people will choose to search online and use Youdao, Kingsoft PowerWord, etc. to translate. In fact, Excel itself can be translated. If you encounter a language you don't understand, you don't have to bother to look it up online. You can just translate it directly in Excel. This greatly saves time and improves work efficiency. So, let’s talk to you today about how to use the translation function in excel! 1. Open excel, find the &quot;Review&quot; button in the upper menu bar, and click it with the mouse. 2. You can clearly see the word &quot;Translate&quot; below. Click &quot;Translate&quot; and you will see the &quot;Information Search&quot; column appear on the right side of the table. 3. Want to translate “life”

How to solve the problem that Google Chrome cannot start the translation function How to solve the problem that Google Chrome cannot start the translation function Jan 31, 2024 pm 02:00 PM

What should I do if the Google Chrome translation function fails to start? When many friends use Google Chrome, they will find that its translation function sometimes fails to start, which greatly affects our normal use. Usually, the failure to start the translation function is usually due to internal settings problems. Of course, factors such as browser failures are not excluded. So, how do we solve the problem of failure to start the translation function? Below, the editor will bring you the solution to the failure to start the Google Chrome translation function. Solution to the failure to start the Google Chrome translation function 1. Open Google Chrome 2. After entering, click the three dots above 3. Then select Settings from the expanded options 4. After entering, select the language 5. Click to add language 6. Add English 7 .Check Ask whether to translate web pages in this language 8. Click

How to set up English webpage pop-up translation function in edge browser How to set up English webpage pop-up translation function in edge browser Mar 27, 2024 pm 04:16 PM

How to set up the automatic translation function of English web pages in edge browser? Everyone should know that when using the edge browser to browse the web, users can right-click on a blank space on the page and select Translate to Chinese. However, if they want to automatically translate an English website, they need to set it up. How to set up the edge browser to automatically translate English web pages into Chinese. First, we need to start the Edge browser on the computer, then find and click the "..." button in the upper right corner of the browser page, and then select the "Settings" option from the drop-down menu. 2. In the second step, after entering the settings page of the Edge browser, we click to open the "Language" option in the list on the left. 3. The third step, enter

PHP WeChat development: How to implement message encryption and decryption PHP WeChat development: How to implement message encryption and decryption May 13, 2023 am 11:40 AM

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

How to make Google Chrome automatically translate into Chinese How to make Google Chrome automatically translate into Chinese Mar 19, 2024 am 09:13 AM

How to make Google Chrome automatically translate into Chinese? Google Chrome is a super easy-to-use browser software. This browser is fast, safe, and stable. It is very suitable for users to work, study, and entertain. In this browser, we will access pure English pages. , at this time you can turn on the automatic translation function to easily help everyone translate the page content. Next, the editor will bring you a tutorial on how to enable the automatic translation function in Google Chrome. I hope it will be helpful to you. Overview of the tutorial for turning on the automatic translation function in Google Chrome. First, open Google Chrome on your computer, then move the mouse to the three dots in the upper right corner of the screen and click on this icon. 2. Then, a menu option will appear below the three-dot icon.

See all articles