<?php
define("CURL_TIMEOUT", 30);
define("URL", "http://api.fanyi.baidu.com/api/trans/vip/translate");
define("APP_ID", "YOUR APP ID"); //替换为您的APPID
define("SEC_KEY", "YOUR SEC KEY");//替换为您的密钥
define("FROM", "zh");//采集的源语言标识码,默认为中文“zh”
define("TO", "en");//翻译后的目标语言标识码,默认翻译为英文“en”
function translate($query)
{
$args = array(
'q' => $query,
'appid' => APP_ID,
'salt' => rand(10000,99999),
'from' => FROM,
'to' => TO,
);
$args['sign'] = buildSign($query, APP_ID, $args['salt'], SEC_KEY);
$ret = call(URL, $args);
$ret = json_decode($ret, true);
if (isset($ret['error_code']))
{
switch ($ret['error_code'])
{
case 52003:
return "错误代码(".$ret['error_code']."):APP_ID不正确,请检查您填写的APP_ID是否和百度翻译开放平台申请的一致。";
break;
case 54001:
return "错误代码(".$ret['error_code']."):密钥不正确,请检查您填写的密钥是否和百度翻译开放平台申请的一致。";
break;
case 54000:
return "错误代码(".$ret['error_code']."):翻译内容为空,请检查您的采集规则是否正确,出现本错误可能软件未采集到内容。";
break;
case 54004:
return "错误代码(".$ret['error_code']."):余额不足,您的免费字符已用完或余额不足,请登陆百度翻译开放平台充值。";
break;
case 58001:
return "错误代码(".$ret['error_code']."):译文语言方向错误,请检查您设置的目标语言标识码是否正确。";
break;
default:
return "错误代码(".$ret['error_code']."):不可预知的错误,请登陆http://www.sizuo.org/locoy-baidutransapi.html查看解决方案。";
break;
}
}
return $ret["trans_result"]["0"]["dst"];
}
function buildSign($query, $appID, $salt, $secKey)
{
$str = $appID . $query . $salt . $secKey;
$ret = md5($str);
return $ret;
}
function call($url, $args=null, $method="post", $testflag = 0, $timeout = CURL_TIMEOUT, $headers=array())
{
$ret = false;
$i = 0;
while($ret === false)
{
if($i > 1)
break;
if($i > 0)
{
sleep(1);
}
$ret = callOnce($url, $args, $method, false, $timeout, $headers);
$i++;
}
return $ret;
}
function callOnce($url, $args=null, $method="post", $withCookie = false, $timeout = CURL_TIMEOUT, $headers=array())
{
$ch = curl_init();
if($method == "post")
{
$data = convert($args);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
}
else
{
$data = convert($args);
if($data)
{
if(stripos($url, "?") > 0)
{
$url .= "&$data";
}
else
{
$url .= "?$data";
}
}
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(!empty($headers))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
if($withCookie)
{
curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
}
$r = curl_exec($ch);
curl_close($ch);
return $r;
}
function convert(&$args)
{
$data = '';
if (is_array($args))
{
foreach ($args as $key=>$val)
{
if (is_array($val))
{
foreach ($val as $k=>$v)
{
$data .= $key.'['.$k.']='.rawurlencode($v).'&';
}
}
else
{
$data .="$key=".rawurlencode($val)."&";
}
}
return trim($data, "&");
}
return $args;
}
if($LabelArray['PageType']=="Save")
{
$LabelArray['标题'] = translate($query = $LabelArray['标题']);
$LabelArray['翻译的内容'] = translate($query = $LabelArray['内容']);
}
echo serialize($LabelArray);
?>
网上找的,API要申请,然后Token自己填写进去