class TransController {
public $URL = "https://fanyi-api.baidu.com/api/trans/vip/translate";
public $CURL_TIMEOUT = 10;
public $APP_ID = "201702xxxxxxxx";
public $SEC_KEY = "SRuOMvxxxxxxx";
public function _initialize() {
parent::_initialize();
}
public function index() {
set_time_limit(0);
$this->trans_product();
die("all ok");
}
/**
* 翻译产品内容
*/
private function trans_product() {
$table_name = 'product';
$field = "title";
$list = M($table_name)->order("id asc")->select();
$pattern = '/[\x{4e00}-\x{9fa5}]+/u'; //匹配中文然后替换
foreach ($list as $k => $v) {
$str = trim($v[$field]);
$matches = array();
preg_match_all($pattern, $str, $matches);
if (count($matches[0]) > 0) {
$one_q = "";
foreach ($matches[0] as $m => $n) {
$one_q .= $n . "\n";
}
$res = $this->translate($one_q);
if (count($res['trans_result']) > 0) {
foreach ($res['trans_result'] as $o => $p) {
$str = str_replace($p['src'], $p['dst'], $str);
}
$up_data = array("id" => $v['id'], $field => $str);
M($table_name)->save($up_data);
sleep(2);
} else {
echo $v['id'];
}
}
}
}
//翻译入口
private function translate($query, $from = "zh", $to = "en") {
$args = array(
'q' => $query,
'appid' => $this->APP_ID,
'salt' => rand(10000, 99999),
'from' => $from,
'to' => $to,
);
$args['sign'] = $this->buildSign($query, $this->APP_ID, $args['salt'], $this->SEC_KEY);
$ret = $this->call($this->URL, $args);
$ret = json_decode($ret, true);
return $ret;
}
//加密
private function buildSign($query, $appID, $salt, $secKey) {/* {{{ */
$str = $appID . $query . $salt . $secKey;
$ret = md5($str);
return $ret;
}
/* }}} */
//发起网络请求
private function call($url, $args = null, $method = "post", $testflag = 0, $timeout = 10, $headers = array()) {/* {{{ */
$ret = false;
$i = 0;
while ($ret === false) {
if ($i > 1)
break;
if ($i > 0) {
sleep(1);
}
$ret = $this->callOnce($url, $args, $method, false, $timeout, $headers);
$i++;
}
return $ret;
}
/* }}} */
private function callOnce($url, $args = null, $method = "post", $withCookie = false, $timeout = 10, $headers = array()) {/* {{{ */
$ch = curl_init();
if ($method == "post") {
$data = $this->convert($args);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_POST, 1);
} else {
$data = $this->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;
}
/* }}} */
private 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;
}
/* }}} */
}