我正在尝试使用Google API和PHP curl转换货币数据。不幸的是我有以下问题,我仍然无法解决它。任何人都可以帮助我。 这是我的PHP函数。
function currency($from_Currency,$to_Currency,$amount) {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
$data = explode(' ', $data['3']);
$var = $data['0'];
return round($var,2);
}
//这是我的函数调用
$usd= currency("USD","ETB",1);
echo "270 USD= ".$usd."ETB";
但我有以下错误
注意:未定义的偏移量:3 ...在线....(此功能的14个)
答案 0 :(得分:1)
您的API网址似乎有误,因为当$rawdata
回显时,Google会返回错误404.目前,可用的解决方案(如果您坚持使用Google)是使用Google转换货币金融。例如,使用GET
请求,您可以使用以下格式发送请求:
$url = "https://www.google.com/finance/converter?a=" . $amount . "&from=" . $from . "&to=" . $to;
不幸的是,Google会返回整页HTML,因此您需要手动解析结果。我刚刚尝试使用https://www.google.com/finance/converter?a=1&from=IDR&to=USD访问它,转换结果附加在<div>
中,如下所示:
<div id=currency_converter_result>1 IDR = <span class=bld>0.0001 USD</span>
因此,如果将结果保存在$rawdata
变量中,则可以在PHP中使用正则表达式来获取转换结果。由于它不是正式的API,因此如果代码无效,您需要在下次主动查看页面结构。
这是您的代码,使用测试更新:
function convertCurrency($amount, $from_Currency, $to_Currency) {
$url = "https://www.google.com/finance/converter?a=" . $amount . "&from=" . $from_Currency . "&to=" . $to_Currency;
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$rawdata = curl_exec($ch);
curl_close($ch);
preg_match("/<span class=bld>(.*)<\/span>/", $rawdata, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted);
return round($converted[0], 3);
}
$usd = currency("USD", "ETB", 270);
echo "270 USD = " . $usd . " ETB";
我的建议是:找另一种货币转换API。您可以查找https://openexchangerates.org/之类的替代方案。不幸的是,它是一项付费服务。
答案 1 :(得分:0)
Google已将其网址更改为
https://www.google.com/finance/converter?a
试试这个
function currency($from_Currency,$to_Currency,$amount) {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$get = file_get_contents("https://www.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency");
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);
return round($converted_amount,2);
}
echo currency("USD","INR",2);