当前位置:
首页 > 技术 > php 世界各国实时汇率对换率代码

php 世界各国实时汇率对换率代码

调用php代码,从百度api接口调用即时的汇率信息,支持的货币及国家请查看百度的文档。

/*===== start exchange rate =====*/
/**
* Exchange Currency
* apikey: impersonal
* url: http://apistore.baidu.com/apiworks/servicedetail/119.html
*/
function ExchangeCurrency($Amount, $fromCurrency="CNY", $toCurrency="USD")
{
     $ch = curl_init();
     $url = 'http://apis.baidu.com/apistore/currencyservice/currency?fromCurrency='.$fromCurrency.'&toCurrency='.$toCurrency.'&amount='.$Amount;
     $header = array(
          'apikey: xxx',
     );
     // 添加apikey到header
     curl_setopt($ch, CURLOPT_HTTPHEADER , $header);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch , CURLOPT_URL , $url); // 执行HTTP请求
     $json = curl_exec($ch);
     // var_dump(json_decode($res));
     $decode = json_decode($json);
     if($decode->errMsg =='success')
     {
          $res = $decode->retData;
     }else{
          $res = 'Error Number:'.$decode->errNum;
     }

     return $res;
}
/*===== end exchange rate =====*/

该代码用于把结果写入到本地缓存文件中,就不用打开页面都去调用,减少调用频率

/**
 * write into text for real time exchange rate
 */
function WriteRTE($filename)
{
	global $timestamp;
	$eCU=ExchangeCurrency(1, 'CNY', 'USD');
	$eUC=ExchangeCurrency(1, 'USD', 'CNY');
	$date = $eCU->date ."\n"; //0
	$time = $eCU->time ."\n"; //1
	$CtU = $eCU->currency ."\n"; //2
	$UtC = $eUC->currency ."\n"; //3
	$UPDate = $timestamp; //4

	$str = $date. $time. (empty($CtU)?0:$CtU). (empty($UtC)?0:$UtC). $UPDate;
	WriteLog($str, $filename, true);

	$res = array('RTEDate'=>$date, 'RTETime'=>$time, 'CNYtoUSD'=>$CtU, 'USDtoCNY'=>$UtC);
	return $res;
}

该方法用于指定每8个小时重新更新一次

function varCom()
{//'ProfitRate', 'Freight', 'ExchangeRate', 'Commission', 'UserAgent', 'RefererUrl', 'ImgDir'
	global $timestamp, $RTEfn;

	// real time exchange rate
	$RTE = InquireFile($RTEfn);
	if($RTE)
	{
		$RTEArr = explode("\n", $RTE);
		$diff = 8 * 60 * 60; //8 hours
		if( $timestamp - $RTEArr[4] > $diff  ) //every 8 hours update once.
		{
			$cgArr = array_merge($cgArr, WriteRTE($RTEfn));
		}else{
			$cgArr['RTEDate'] = $RTEArr[0];
			$cgArr['RTETime'] = $RTEArr[1];
			$cgArr['CNYtoUSD'] = $RTEArr[2];
			$cgArr['USDtoCNY'] = $RTEArr[3];
		}
	}else{
		$cgArr = array_merge($cgArr, WriteRTE($RTEfn));
	}

	return $cgArr;
}

读指定文件

/**
 * read file
 */
function InquireFile($file, $type='.txt', $dir)
{
    global $CacheDir;
    $dir = empty($dir) ? $CacheDir : $dir;
    return file_get_contents($dir . $file . $type);
}
$timestamp = time(); //time stamp
$RTEfn = 'RTExchange'; //real time exchange file name.
$cg = varCom(); //common variable

php 世界各国实时汇率对换率代码:等您坐沙发呢!

发表评论

您必须 [ 登录 ] 才能发表留言!