6.PHP微信公眾平臺開發 - 翻譯功能開發

發表於2019-05-11

【PHP微信公眾平臺開發系列】
01.配置微信介面
02.公眾平臺示例程式碼分析
03.訂閱事件(subscribe)處理
04.簡單回覆功能開發
05.天氣預報功能開發
06.翻譯功能開發


一、簡介
上一篇文章介紹了微信公眾平臺天氣預報功能的開發,實現了微信公眾平臺的第一個實際應用,在接下來的這一篇文章中,我們將對微信翻譯功能進行簡單開發,以供讀者參考。
二、思路分析
和上一篇查詢天氣的思路差不多,首先要對使用者傳送過來的訊息進行判斷,判斷訊息裡是否含有“翻譯”關鍵字,如果含有,則提取待翻譯內容,然後呼叫網路上開放的翻譯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
按照要求填寫相關資訊,這些資訊,下面會使用到,所以請認真如實填寫。

申請完之後,會在下方生成API key 和keyfrom,使用API 時會用到。

3.1.3 API 使用範例

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 格式:

百度翻譯:

評論(2)

相關文章