PHP自建一个翻译API(采用百度开放接口),测试环境:Nginx 1.22.1 + PHP7.4/8.0
<?php
/**
* @desc 百度文档翻译服务接口
* 计数服务接口校验同理,完整文档参考:https://fanyi-api.baidu.com/doc/21
*/
header('Access-Control-Allow-Origin:*');
header('Content-type: application/json');
$word=isset($_GET['text'])? $_GET['text'] :null;
if(empty($word)){die("请传入text参数");}
$des=isset($_GET['to'])? $_GET['to'] :null;
if(!empty($des)){
$aim = $des;
}else{
if (preg_match("/([\x81-\xfe][\x40-\xfe])/", $word, $match)) {
//含有汉字
$aim = 'en';
} else {
//不含有汉字
$aim = 'zh';
}
}
$appid = 'APP ID'; //你自己的Appid
$seckey = '密钥'; //你的密钥
$salt = '1435660288'; //随机数,你也可以用10位时间戳
$params = array(
'appid' => $appid,
'from' => 'auto',
'to' => $aim,
'salt' => $salt,
'q' => $word,
);
ksort($params);
$querySign = '';
$params['sign'] = md5($appid.$word.$salt.$seckey);
foreach ($params as $key => $value) {
$querySign .= $key . '=' . $value . '&';
}
$url = 'http://fanyi-api.baidu.com/api/trans/vip/translate?';
$header = array(
'Content-Type' => 'application/x-www-form-urlencoded',
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$querySign);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
$callRet = json_decode($result, true);
$src = $callRet['trans_result'][0]['src'];
$dst = $callRet['trans_result'][0]['dst'];
header("content-type: application/json");
$json_return = array(
"code" => '200',
"src" => $src,
"dst" => $dst
);
echo json_encode($json_return, JSON_UNESCAPED_UNICODE);
?>
接口文档:https://api.szfx.top/api/fanyi.html
实践案例:https://tool.szfx.top/fanyi
百度翻译开放平台:https://fanyi-api.baidu.com/
2022年8月1日起,通用翻译API标准版免费调用量调整为5万字符/月,高级版免费调用量调整为100万字符/月