PHP_有道翻译

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

 $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= "";
foreach ($res['translation'] as $k=>$v) {
    $return .= $v.";";
}
$return .= "";
echo $return;
exit;
?>

你可能感兴趣的:(PHP_有道翻译)