/***************************************************************************
* Copyright (c) Baidu.com, Inc. All Rights Reserved *
**************************************************************************/
/**
* @file baidu_transapi.php
* @author Mouyantao (mouyantao@baidu.com)
* @date 2015/06/23 14:32:18
* @brief
*
**/
Define ("Curl_timeout", 10);
Define ("URL", "http://api.fanyi.baidu.com/api/trans/vip/translate");
Define ("APPID", "YOUR APP ID"); Replace with your AppID
Define ("Password", "YOUR SEC Key");//Replace with your key
Translation Portal
function translate ($query, $from, $to)
{
$args = Array (
' Q ' = $query,
' AppID ' = app_id,
' Salt ' = rand (10000,99999),
' From ' = $from,
' To ' and $to,
);
$args [' sign '] = Buildsign ($query, app_id, $args [' salt '], sec_key);
$ret = Call (URL, $args);
$ret = Json_decode ($ret, true);
return $ret;
}
Encryption
function Buildsign ($query, $appID, $salt, $secKey)
{/*{{{*/
$str = $appID. $query. $salt. $secKey;
$ret = MD5 ($STR);
return $ret;
}/*}}}*/
Initiating a network request
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;
}/*}}}*/
?>
Reply to discussion (solution)
Call directly on it, but first you have to apply for a app_id in Baidu
Call directly on it, but first you have to apply for a app_id in Baidu
I have applied for it. But not very good, there is an HTM version of you to see
Open Browser Console to view results