ThinkPHP调用百度翻译类实现在线翻译
要实现ThinkPHP在线翻译功能,需要先在百度开发者中心注册一个APIkey,具体实现代码如下:
action代码部分:
<?php
classFanyiActionextendsAction{
publicfunction_empty(){
header("HTTP/1.0404NotFound");
$this->display("Public:404");
}
publicfunctionindex()
{
$User=A("Index");
$User->head();
$User->right();
$User->footer();
$this->display();
}
publicfunctionfanyi()
{
$value=$_POST['value'];
$from="auto";
$to="auto";
$value_code=urlencode($value);
$appid="xxxxxxxx";//这里填写你在百度上申请的APIkey
$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);
}
publicfunctionlanguage_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代码部分:
<divid="content">
<divstyle="padding:5px;">
<formaction="__APP__/fanyi/"method="POST"name="fanyi">
<p>原文:</p>
<textareaname="value"id="yuanwen"rows="10"cols="80"style="padding:5px;width:661px;height:217px;">{$value}</textarea>
<inputtype="submit"class="search-submit"value="翻 译"style="text-align:center;">
<inputtype="reset"onclick="reset()"class="search-submit"value="清 空"style="text-align:center;">
</form>
<p>译文:</p>
<textareaname="rs"id="yiwen"rows="10"cols="80"style="padding:5px;width:661px;height:217px;">{$rs}</textarea></div>
</div>热门推荐
10 小学毕业父母简短祝福语
11 幼儿生日祝福语模板简短
12 新娘妈妈的祝福语简短
13 邻居聚会祝福语大全简短
14 十条祝福语简短
15 给同学祝福语的简短
16 过年祝福语简短祝妈妈
17 祝女儿简短祝福语大全
18 恩师诗词祝福语简短大全