一、簡介
上一篇文章介紹了微信公衆平台天氣預報功能的開發,實作了微信公衆平台的第一個實際應用,在接下來的這一篇文章中,我們将對微信翻譯功能進行簡單開發,以供讀者參考。
二、思路分析
和上一篇查詢天氣的思路差不多,首先要對使用者發送過來的消息進行判斷,判斷消息裡是否含有“翻譯”關鍵字,如果含有,則提取待翻譯内容,然後調用網絡上開放的翻譯API 進行相關翻譯。
三、翻譯API 分析
網絡上有很多翻譯API,大家可以根據自己的需求進行選擇。這裡我們選擇應用比較廣泛的,翻譯功能還比較不錯的有道翻譯API 和百度翻譯API,下面對這兩種API的相關資訊進行分析。
3.1 有道翻譯API
3.1.1 API 位址:http://fanyi.youdao.com/openapi
注意:有道提供的API 接口,在下面的測試時,json 資料格式傳回不正确,到網上查閱資料,可以正确翻譯的位址為 http://fanyi.youdao.com/fanyiapi,這點注意。
3.1.2 申請key
按照要求填寫相關資訊,這些資訊,下面會使用到,是以請認真如實填寫。

3.1.4 資料格式
a. xml 格式
http://fanyi.youdao.com/openapi.do?keyfrom=orchid&key=1008797533&type=data&doctype=xml&version=1.1&q=這裡是有道翻譯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>
b. json 格式
http://fanyi.youdao.com/openapi.do?keyfrom=orchid&key=1008797533&type=data&doctype=json&version=1.1&q=翻譯
{
"errorCode":0
"query":"翻譯",
"translation":["translation"], // 有道翻譯
"basic":{ // 有道詞典-基本詞典
"phonetic":"fān yì",
"explains":[
"translate",
"interpret"
]
},
"web":[ // 有道詞典-網絡釋義
{
"key":"翻譯",
"value":["translator","translation","translate","Interpreter"]
},
{...}
]
}
3.2 百度翻譯API
3.2.1 API 位址:http://openapi.baidu.com/public/2.0/bmt/translate
3.2.2 擷取api key
開發者在百度連接配接平台上注冊得到的授權API key,詳細請參閱: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 使用範例
3.2.4 資料格式
百度翻譯API 響應的資料格式為UTF-8編碼的PHP數組對應的标準JSON字元串。
{
“from”:”zh”,
“to”:”en”,
“trans_result”:[]
}
trans_result 為一個數組,其中每一個{}就是一個段落,結構如下所示:
trans_result: [
{},
{},
{}
]
段落結果即為trans_result 數組中的一項:
{
“src”:””,
“dst”:””
}
段落結果說明:
經json_decode 後的形式:
{
"from": "en",
"to": "zh",
"trans_result": [
{
"src": "today",
"dst": "今天"
}
]
}
四、關鍵字判斷與待翻譯内容讀取
翻譯消息的格式是 “翻譯+待翻譯内容”,是以首先截取前兩個字,判斷是否為 “翻譯” 關鍵字。
使用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);
五、具體實作
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 格式
關鍵代碼如下:
public function youdaoDic($word){
$keyfrom = "orchid"; //申請APIKEY 時所填表的網站名稱的内容
$apikey = "YourApiKey"; //從有道申請的APIKEY
//有道翻譯-xml格式
$url_youdao = 'http://fanyi.youdao.com/fanyiapi.do?keyfrom='.$keyfrom.'&key='.$apikey.'&type=data&doctype=xml&version=1.1&q='.$word;
$xmlStyle = simplexml_load_file($url_youdao);
$errorCode = $xmlStyle->errorCode;
$paras = $xmlStyle->translation->paragraph;
if($errorCode == 0){
return $paras;
}else{
return "無法進行有效的翻譯";
}
}
說明:
$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 = 'http://fanyi.youdao.com/fanyiapi.do?keyfrom='.$keyfrom.'&key='.$apikey.'&type=data&doctype=json&version=1.1&q='.$word;
$jsonStyle = file_get_contents($url_youdao);
$result = json_decode($jsonStyle,true);
$errorCode = $result['errorCode'];
$trans = '';
if(isset($errorCode)){
switch ($errorCode){
case 0:
$trans = $result['translation']['0'];
break;
case 20:
$trans = '要翻譯的文本過長';
break;
case 30:
$trans = '無法進行有效的翻譯';
break;
case 40:
$trans = '不支援的語言類型';
break;
case 50:
$trans = '無效的key';
break;
default:
$trans = '出現異常';
break;
}
}
return $trans;
}
$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字元串,而且提供了 中->英,中->日,英->中,日->中 四種互譯,比有道翻譯多了一種。
//百度翻譯
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('file_get_contents')){
$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;
}
這裡包含了兩個函數,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 格式:
百度翻譯:
七、完整代碼擷取
請通路 樂思樂享 官方網盤
URL:http://pan.baidu.com/s/1c0s3Jby
八、關注
請關注 卓錦蘇州 微信公衆帳号,卓錦蘇州 基于BAE 平台開發,針對于主流的微信功能進行開發測試。
您可以關注 卓錦蘇州 公衆帳号進行功能測試,以及擷取新的應用開發。
1. 登入微信用戶端,通訊錄 -> 添加朋友 -> 查找公衆号 -> zhuojinsz,查找并關注。
2. 掃描二維碼:
卓錦蘇州 功能清單。
David Camp
我們永遠相信,分享是一種美德 | We Believe, Great People Share Knowledge...