|
要實現Thinkphp在線翻譯功能,需要先在百度開發者中心注冊一個API key,具體實現代碼如下:
action代碼部分:
<?phpclass FanyiAction extends Action {public function _empty(){ header("HTTP/1.0 404 Not Found"); $this->display("Public:404"); }public function index(){$User = A("Index"); $User->head();$User->right();$User->footer();$this->display();}public function fanyi(){$value=$_POST['value'];$from="auto";$to="auto";$value_code=urlencode($value); $appid="xxxxxxxx";//這里填寫你在百度上申請的API key $languageurl = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=" . $appid ."&q=" .$value_code. "&from=".$from."&to=".$to;$text=json_decode($this->language_text($languageurl)); $text = $text->trans_result; $rs=$text[0]->dst;$this->assign('value',$value);$this->assign('rs',$rs);$User = A("Index"); $User->head();$User->right();$User->footer();$this->display(index);}public function language_text($url) //獲取目標URL所打印的內容{ if(!function_exists('file_get_contents')) { $file_contents = file_get_contents($url); } else { $ch = curl_init(); $timeout = 5; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $file_contents = curl_exec($ch); curl_close($ch); } return $file_contents;}}?>
html代碼部分:
<div id="content"><div style="padding:5px;"><form action="__APP__/fanyi/" method="POST" name="fanyi"><p>原文:</p><textarea name="value" id="yuanwen" rows="10" cols="80" style="padding:5px;width: 661px; height: 217px;">{$value}</textarea><input type="submit" class="search-submit" value="翻 譯" style="text-align:center;"> <input type="reset" onclick="reset()" class="search-submit" value="清 空" style="text-align:center;"></form><p>譯文:</p><textarea name="rs" id="yiwen" rows="10" cols="80" style="padding:5px;width: 661px; height: 217px;">{$rs}</textarea> </div></div>
php技術:ThinkPHP調用百度翻譯類實現在線翻譯,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。