欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ThinkPHP调用百度翻译类实现在线翻译

程序员文章站 2023-11-12 22:08:40
要实现thinkphp在线翻译功能,需要先在百度开发者中心注册一个api key,具体实现代码如下: action代码部分:

要实现thinkphp在线翻译功能,需要先在百度开发者中心注册一个api key,具体实现代码如下:

action代码部分:

<?php
class 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>