1)Google翻譯介面
2)微信呼叫
3)效果展示
------------------------------ -------------------------------------------------- --------
1)Google翻譯介面
Google提供翻譯的API介面,請參閱https://developers.google.com/translate/v2/getting_started
but
Google Translate API is a paid service.
so
想利用Google Translate API free charge 就要另外想辦法了
Google提供免費的線上翻譯功能,因此,可以透過Web發送翻譯請求給Google,接收它的html返回,然後,透過分析html取得翻譯後的文字.
function translate_web($text, $language="auto|en") { if (empty($text)) return false; $url = "http://google.cn/translate_t?ie=UTF-8&oe=UTF-8&langpair=".$language."&text=".urlencode($text); $html=file_get_contents($url); // parse html // html souce: TTS_TEXT_SIZE_LIMIT=100;TRANSLATED_TEXT='世界,你好!';INPUT_TOOL_PATH='//www.google.com'; $mode= ("/TRANSLATED_TEXT='(.*)';INPUT_TOOL_PATH/"); if (preg_match($mode,$html,$out)){ return $out[1];//ret; } }
更有什者,有人發現透過http://translate.google.com/translate_a/t?client=p與Google交互可以得到json返回,這就相當於API使用了
function translate_json($text, $language="auto|en") { if (empty($text)) return false; $url = "http://translate.google.cn/translate_a/t?client=p&ie=UTF-8&oe=UTF-8&langpair=".$language."&text=".urlencode($text); $json=file_get_contents($url); $data = json_decode($json); return $data->sentences[0]->trans; }
Google翻譯介面範例: http://download.csdn.net/detail/d_eng/6563915
這裡要注意的有兩個問題
1)編碼問題,例子中都採用utf-例子中都採用utf- 8,連php檔案的屬性都是utf-8
2)google問題,google在中國不保證一直能連上,雖然有多個連結google.com/google.cn/google.com.hk
2 )微信呼叫
有了介面,在微信中呼叫就簡單了
介面檔translate_func.php (save as utf-8)
t)&default code=GBK function translate_json() d_eng (sh109419@163.com) 2013-11-16 */ /* Google Translate WEB IF get translated text by parsing return html which code is GBK */ //header("Content-Type:text/html; charset=utf-8"); function translate_web($text, $language="auto|en") { if (empty($text)) return false; $url = "http://google.cn/translate_t?ie=UTF-8&oe=UTF-8&langpair=".$language."&text=".urlencode($text); $html=file_get_contents($url); // parse html // html souce: TTS_TEXT_SIZE_LIMIT=100;TRANSLATED_TEXT='世界,你好!';INPUT_TOOL_PATH='//www.google.com'; $mode= ("/TRANSLATED_TEXT='(.*)';INPUT_TOOL_PATH/"); if (preg_match($mode,$html,$out)){ return $out[1];//ret; } } function translate_json($text, $language="auto|en") { if (empty($text)) return false; $url = "http://translate.google.cn/translate_a/t?client=p&ie=UTF-8&oe=UTF-8&langpair=".$language."&text=".urlencode($text); $json=file_get_contents($url); $data = json_decode($json); return $data->sentences[0]->trans; } function with_chinese($text){ return preg_match('/[\x7f-\xff]/',$text); } function translate($text) { if (with_chinese($text)) { return translate_json($text,'zh-CN|en'); } else { return translate_json($text,'en|zh-CN'); } } ?>
呼叫程式碼片段
if ($RX_TYPE=="text") { include("translate_func.php"); $resultStr = $this->responseText($postObj, translate(trim($postObj->Content))); }
3)效果顯示
rrreee呼叫程式碼片段rrreee
3)效果展示微信公眾平台開發--Google翻譯的內容,更多相關內容請關注PHP中文網(m.sbmmt.com)!