当一回雷锋容易,持续发扬雷锋精神就难了(百度翻译接口php写法),下面我就4414站长的小小白站长们,提供百度接口PHP写法的例子。声明我这个是基于应该算是大众的了。首先不清楚您的CMS有没有自带的memcached与redis。如果有请把相关代码删除掉。另外就是post字段那里请根据自己的CMS做好变量过滤处理。不扯淡了,直接上干货,代码如下:
- <?php
-
- $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();
- }
- });
-
- 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 = '';
- $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);
- 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);
- }
- $access_token_baidu =$ret['access_token'];
- $postDatafy= [
- 'from' =>'auto',
- 'to' => $_POST['category'],
- 'q' =>$_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);
api后端接口就写好了哦,那我们命名为baidufanyi.php,其实百度所有的接口开发流程就是这样的,先获取百度独有的token(这里应该设为缓存,好像1个月内是不过期的,减少点curl时间的花销),而后在请求相关的接口。好人做到底,那顺便也把前端也写个例子,代码如下:
- 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);
- },
- });