php+google/baidu翻译接口
<?php
/**
* @link http://www.joinf.com
* @copyright Copyright (C) 2017 joinf.com. All rights reserved.
*/ namespace site\admin\controller; use site\admin\model\LanguageModel; /**
* 翻译管理
*/
class TranslateController extends \site\admin\component\Controller
{ private $appid;
private $seckey;
private $_model; /**
* 初始化
* @access public
* @return void
*/
public function __construct()
{
$this->_model = new LanguageModel();
$translate=$this->_model->getTranslate();
if($translate){
$this->appid=$translate['appid'];
$this->seckey=$translate['seckey'];
}else{
$this->appid='';
$this->seckey='';
}
} /**
* 翻译接口
*
* POST:source_id=原始语言ID,dest_ids=目标语言(数组格式),txts=数据源(数组格式)
*
* @access public
* @return void
*/
public function toLanguage()
{
/* $this->request->post= [
'source_id' => '1',
'dest_ids' => ["2",'3'],
'txts' =>['今天天气不错,挺风和日丽的','我们都有一个家,名字叫中国'],
]; */ //google翻译接口
$language_id=isset($this->request->post['source_id'])?$this->request->post['source_id']:'';
$dest_ids=isset($this->request->post['dest_ids'])?$this->request->post['dest_ids']:'';
$data = isset($this->request->post['txts']) ? $this->request->post['txts']: ''; if(empty($language_id)||empty($dest_ids)||empty($data)){ $this->flash('error', '参数错误');
return $this->formatResponse(); }else{
//获取源语种
$b_l=explode(',',$this->config->get('sys_google_translate_code'));
$url=$this->config->get('sys_google_translate_url'); foreach ($b_l as $k=>$v){
if(($k+1)==$language_id){
$source=$v;
}
} $t_data=array(); foreach ($dest_ids as $kk=>$vv){
//计算翻译目标语种
foreach ($b_l as $k=>$v){
if(($k+1)==$vv){
$target=$v;
}
} //组装译文
$translist=array();
foreach ($data as $key=>$value){
//初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, $url);
//设置头文件的信息作为数据流输出
curl_setopt($curl, CURLOPT_HEADER, 1);
//设置获取的信息以文件流的形式返回,而不是直接输出。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//设置post方式提交
curl_setopt($curl, CURLOPT_POST, 1);
//设置post数据
$post_data = array(
"q" => $value,
"source" => $source,
"target" => $target,
'format' => 'text'
);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
//执行命令
$exec_data = curl_exec($curl);
//关闭URL请求
curl_close($curl);
//显示获得的数据
$result=json_decode(strstr($exec_data,'{'),true);
$translist[]=$result['data']['translations'][0]['translatedText'];
}
//该语种全部译文
$t_data[$vv]=$translist;
}
$this->manageLogModel->add('多语言翻译');
$this->flash('success', '翻译成功');
$this->formatResponse($t_data);
} //百度翻译接口
/* $language_id=isset($this->request->post['source_id'])?$this->request->post['source_id']:'';
$dest_ids=isset($this->request->post['dest_ids'])?$this->request->post['dest_ids']:'';
$data = isset($this->request->post['txts']) ? $this->request->post['txts']: ''; if(empty($language_id)||empty($dest_ids)||empty($data)){ $this->flash('error', '提交错误');
return $this->formatResponse(); }else{
//获取源语种
$b_l=explode(',',$this->config->get('sys_baidu_language_code')); foreach ($b_l as $k=>$v){
if(($k+1)==$language_id){
$from=$v;
}
} $t_data=array();
$count_num=0;
foreach ($dest_ids as $kk=>$vv){
//计算翻译目标语种
foreach ($b_l as $k=>$v){
if(($k+1)==$vv){
$to=$v;
}
}
//组装译文
$translist=array();
foreach ($data as $key=>$value){
$result=$this->translate($value,$from,$to);
$translist[]=$result['trans_result'][0]['dst'];
$count_num+=mb_strlen($value,'utf-8');
}
//该语种全部译文
$t_data[$vv]=$translist;
}
$this->_model->updateTranslate($this->appid,$count_num,time());
$this->manageLogModel->add('多语言翻译');
$this->flash('success', '翻译成功');
$this->formatResponse($t_data);
} */ } //翻译入口
public function translate($query, $from, $to){
$args = array(
'q' => $query,
'appid' => $this->appid,
'salt' => rand(10000,99999),
'from' => $from,
'to' => $to,
);
$args['sign'] = $this->buildSign($query, $this->appid, $args['salt'], $this->seckey);
$ret = $this->call($this->config->get('sys_baidu_url'), $args,'post',0,$this->config->get('sys_baidu_curl_timeout'));
$ret = json_decode($ret, true);
return $ret;
} //加密
public function buildSign($query, $appID, $salt, $secKey){
$str = $appID . $query . $salt . $secKey;
$ret = md5($str);
return $ret;
} //发起网络请求
public function call($url, $args=null, $method="post", $testflag = 0, $timeout = 0, $headers=array()){
$ret = false;
$i = 0;
while($ret === false)
{
if($i > 1)
break;
if($i > 0)
{
sleep(1);
}
$ret = $this->callOnce($url, $args, $method, false, $timeout, $headers);
$i++;
}
return $ret;
} public function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = 0, $headers=array()){
$ch = curl_init();
if($method == "post")
{
$data = $this->convert($args);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
}
else
{
$data = convert($args);
if($data)
{
if(stripos($url, "?") > 0)
{
$url .= "&$data";
}
else
{
$url .= "?$data";
}
}
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(!empty($headers))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if($withCookie)
{
curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
}
$r = curl_exec($ch);
curl_close($ch);
return $r;
} public function convert(&$args){
$data = '';
if (is_array($args))
{
foreach ($args as $key=>$val)
{
if (is_array($val))
{
foreach ($val as $k=>$v)
{
$data .= $key.'['.$k.']='.rawurlencode($v).'&';
}
}
else
{
$data .="$key=".rawurlencode($val)."&";
}
}
return trim($data, "&");
}
return $args;
}
}
php+google/baidu翻译接口的更多相关文章
- .net core 和 WPF 开发升讯威在线客服系统:调用百度翻译接口实现实时自动翻译
业余时间用 .net core 写了一个在线客服系统.并在博客园写了一个系列的文章,写介绍这个开发过程. 我把这款业余时间写的小系统丢在网上,陆续有人找我要私有化版本,我都给了,毕竟软件业的初衷就是免 ...
- 强大的微软Microsoft Translator翻译接口
一.前言 当我们需要对日文.韩文等语言转换中文字符的时候,就用到了微软提供的翻译接口. 二.实现流程 1.首先注册一个账号 https://datamarket.azure.com/account 2 ...
- google谷歌翻译插件-网页一键翻译
上个月转载的一篇博文,是推荐的四款非常实用的翻译插件,这几天看这个chrome插件网首页有新增了一个google谷歌翻译插件.我能说实话,这款插件比之前推荐的4款翻译插件更好用吗?也不能完全说是更好用 ...
- Android性能优化Google课程翻译一:Render----OverDraw实战
Context 近期实战了下OverDraw,加深了下理解.在上篇文章里Android性能优化Google课程翻译一:Render----OverDraw 写过详细方法. OverDraw解决方法离不 ...
- [windows篇] 使用Hexo建立个人博客,自定义域名https加密,搜索引擎google,baidu,360收录
为了更好的阅读体验,欢迎阅读原文.原文链接在此. [windows篇] 使用Hexo建立个人博客,自定义域名https加密,搜索引擎google,baidu,360收录 Part 2: Using G ...
- .net core 和 WPF 开发升讯威在线客服系统:调用有道翻译接口实现实时自动翻译的方法
业余时间用 .net core 写了一个在线客服系统.并在博客园写了一个系列的文章,写介绍这个开发过程. 我把这款业余时间写的小系统丢在网上,陆续有人找我要私有化版本,我都给了,毕竟软件业的初衷就是免 ...
- python爬虫调用谷歌翻译接口
2019年7月4日15:53:17 (¦3[▓▓] 晚安 谷歌翻译环境 Python 3.6 第三方库 Execjs (pip install PyExecJS ) 文件列表 同目录下的四个文件: - ...
- PHP 最完美调用百度翻译接口代码示例 (原)
php调用百度翻译最新接口代码 问 题:写的过程遇到了一个问题,url拼接好的原翻译内容,appid,sign的地址直接输出到浏览器可以打开看到翻译后的返回值,但是各种curl,file_ ...
- Nuxt简单使用Google/Baidu Analyze
博客地址: https://www.seyana.life/post/17 具体账号注册方法和绑定方法可以去到官网下,都有相应的指南, 一般设置也比较简单,只需要把对应js代码添加到head中即可, ...
随机推荐
- HDU 6124 17多校7 Euler theorem(简单思维题)
Problem Description HazelFan is given two positive integers a,b, and he wants to calculate amodb. Bu ...
- 【Python】Excel操作-2 (07版本以下Excel操作,其实不怎么用了,麻蛋,预习了2天课间才发现,还说怎么跟老师讲的不一样)
#保存修改Excel import xlrd from xlutils.copy import copy #打开Excel文档并将内容读取到内存 readbook=xlrd.open_workbook ...
- 在Microsoft Power BI中创建地图的10种方法
今天,我们来简单聊一聊“地图”. 在我们日常生活中,地图地位已经提升的越来越高,出门聚餐.驾驶.坐车.旅行......应运而生的就是各种Map APP. 作为数据分析师,我们今天不讲生活地图,要跟大家 ...
- C#类中字段封装为属性
本文描述内容转载 https://zhidao.baidu.com/question/1174413218458798139.html 感谢 冥冥有你PD 的解答!!! 问题思索1 类成员包括变量和方 ...
- BT原理分析
BT全名為BitTorrent,是一個p2p軟件,你在下載download的同時,也在為其他用戶提供上傳upload,因為大家是「互相幫助」,所以不會隨著用戶數的增加而降低下載速度. 其實跟ED也十分 ...
- 创建文件夹c++
linux #include <sys/types.h> #include <sys/stat.h> string filepath; mkdir(filepath.c_str ...
- MongDB篇,第一章:数据库知识2
MongDB 数据库知识2 非关系型数据库和关系型数据库的比较1. 不是以关系模型构建数据结构,结构比较自由 不保证数据的一致性2. 非关系型数据库弥补了关系型数据库的一些不足,能 够在处理高并 ...
- Dependency Parsing -13 chapter(Speech and Language Processing)
https://web.stanford.edu/~jurafsky/slp3/13.pdf constituent-based 基于成分的phrasal constituents and phras ...
- hdu 1280 堆排序
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s) ...
- 自定义ThreadPoolExecutor带Queue缓冲队列的线程池 + JMeter模拟并发下单请求
.原文:https://blog.csdn.net/u011677147/article/details/80271174 拓展: https://github.com/jwpttcg66/GameT ...