当一回雷锋容易,持续发扬雷锋精神就难了(百度翻译接口php写法),下面我就4414站长的小小白站长们,提供百度接口PHP写法的例子。声明我这个是基于应该算是大众的了。首先不清楚您的CMS有没有自带的memcached与redis。如果有请把相关代码删除掉。另外就是post字段那里请根据自己的CMS做好变量过滤处理。不扯淡了,直接上干货,代码如下:
api后端接口就写好了哦,那我们命名为baidufanyi.php,其实百度所有的接口开发流程就是这样的,先获取百度独有的token(这里应该设为缓存,好像1个月内是不过期的,减少点curl时间的花销),而后在请求相关的接口。好人做到底,那顺便也把前端也写个例子,代码如下:
- <?php
- //内存缓存开始(若您的CMS有给予删除此区间的代码)
- $memcache = null; $redis = null;
- if (class_exists('Memcached')){
- $memcache = new Memcached();
- $memcache->addServer('127.0.0.1', 11211);
- }
- if (class_exists('Redis')){
- $redis = new Redis();
- $redis->connect('127.0.0.1', 6379);
- }
- register_shutdown_function(function() use ($memcache, $redis) {
- if (isset($memcache)) {
- $memcache->quit();
- }
- if (isset($redis)) {
- $redis->close();
- }
- });
- //内存缓存结束(若您的CMS有给予删除此区间的代码)
- function curlRequest($url, $method = 'GET', $data = [], $headers = []) {
- $ch = curl_init($url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- if ($method === 'POST') {
- curl_setopt($ch, CURLOPT_POST, true);
- if (is_array($data) || is_object($data)) {
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
- } else {
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- }
- } elseif ($method !== 'GET') {
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
- if (!empty($data)) {
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
- }
- }
- if (!empty($headers)) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- }
- $response = curl_exec($ch);
- $error = curl_error($ch);
- curl_close($ch);
- if ($error) {
- throw new Exception("CURL Error: " . $error);
- }
- return $response;
- }
- $baiduappid = ''; //到百度申请
- $baiduapikey = '';//应用的API Key;
- $baidusecretkey = '';
- $postData = ['grant_type' =>'client_credentials','client_id' =>$baiduapikey,'client_secret' =>$baidusecretkey];
- $headers = ['Content-Type: application/json','Accept: application/json'];
- $cacheKey = md5($public_r['add_pcurl']).'chatbaidufanyi_access_token_' .$baiduappid;
- $ret= $memcache->get($cacheKey);//若您的CMS有请改成memcache获取缓存的方式
- if ($ret== false) {
- $ret = json_decode(curlRequest("https://aip.baidubce.com/oauth/2.0/token", 'POST', $postData, $headers),TRUE);
- $memcache->set($cacheKey,$ret, 3600*24*28);//若您的CMS有请改成memcache保存缓存的方式
- }
- $access_token_baidu =$ret['access_token'];
- $postDatafy= [
- 'from' =>'auto',
- 'to' => $_POST['category'],//目标语种方向(前端POST传过来的)PS:请根据自己的CMS做好变量过滤处理,比如帝国的过滤函数RepPostStr,那就可以改为RepPostStr($_POST['category'])
- 'q' =>$_POST['content'],//请求翻译文本(前端POST传过来的)PS:请根据自己的CMS做好变量过滤处理,比如帝国的过滤函数RepPostStr,那就可以改为RepPostStr($_POST['content'])
- ];
- $baidufyres =curlRequest("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=".$access_token_baidu,'POST', json_encode($postDatafy));//翻译接口
- $baidufy_array = json_decode($baidufyres, true);
- if(isset($baidufy_array['error_code'])){
- $date= array('result'=>$baidufy_array['error_msg'],'code'=>0,);
- echo json_encode($date);
- exit;
- }
- $date= array('result'=>$baidufy_array['result']['trans_result'][0],'code'=>1,);
- echo json_encode($date);
- var category = $('#category').val();//这是用户填写的翻译的语言方向,如果只翻译为英语。那可以为固定值
- var content = $.trim($("textarea[name=content]").val());//这是用户填写的需要翻译的内容
- if (category== "" || category == null) {
- layer.msg('请选择语言类型', {icon: 5, time: 2000, area: '200px', type: 0, anim: 6,});
- return false;
- }
- if (content== "" || content == null) {
- layer.msg('请输入翻译内容', {icon: 5, time: 2000, area: '200px', type: 0, anim: 6,});
- return false;
- }
- $.ajax({
- url: 'baidufanyi.php',
- type: 'POST',
- data: {category: category,content: content},
- dataType : 'json',
- success: function(json) {
- $("#fyresult").html(json.result.dst);//json.result.dst这个就是后端返回的翻译最终结果json.result.dst
- },
- });