美文网首页
PHP_有道翻译

PHP_有道翻译

作者: 毛子阿卡西 | 来源:发表于2017-08-25 12:00 被阅读0次

    接口文档
    http://ai.youdao.com/docs/api.s#id5

    <?php
    header('Content-Type: text/html; charset=utf-8');
    //报告运行时错误
    ini_set("display_errors","Off");
    error_reporting(E_ERROR | E_WARNING | E_PARSE);
    
    
    //数据
    $data = $_POST;
    $q = $data['q'];
    
    $appid = "6858eedb175aab73";
    $appkey = "ThVLhLwJnYtloa2iYnN9JQH7CnnN5Slx";
    
    $salt = createNonceStr();
    $arr = array(
        "appid" => $appid,
        "q" => $q,
        "salt" => $salt,
        "appkey" => $appkey
        
    );
    $sign = getSign($arr);
    
    
    $post_data = array();
    $post_data['q'] = $q;
    $post_data['from'] = 'zh-CHS';
    $post_data['to'] = 'EN';
    $post_data['appKey'] = $appid;
    $post_data['salt'] = $salt;
    $post_data['sign'] = $sign;
    
    $res = curlPost('http://openapi.youdao.com/api', $post_data);
    $res = json_decode($res,1);
    
    
    function curlPost($url = '', $postData = '', $options = array()) {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数
        if (!empty($options)) {
            curl_setopt_array($ch, $options);
        }
        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    
    function getSign($params) {
        return md5($params['appid'].$params['q'].$params['salt'].$params['appkey']);
    }
    
    function createNonceStr($length = 16) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }
    
    $return= "<span style='width:300px;position:absolute;top:15px;color:red;'>";
    foreach ($res['translation'] as $k=>$v) {
        $return .= $v.";";
    }
    $return .= "</span>";
    echo $return;
    exit;
    ?>
    

    相关文章

      网友评论

          本文标题:PHP_有道翻译

          本文链接:https://www.haomeiwen.com/subject/vfjudxtx.html