我一直在尝试使用PHP中的Google财经转换器转换货币。
我使用了以下代码。
postData[postData.length] = { name: "variable_name", value: variable_value };
但是我收到以下错误
$amount = 100;
$from_Currency = "INR";
$to_Currency = "BTC";
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$get = file_get_contents("https://finance.google.com/finance/converter?a=$amount&from=$from_Currency&to=$to_Currency&meta=ei%3DZsa7WeGkE4_RuASY95SQAw");
$get = explode("<span class=bld>",$get);
$get = explode("</span>",$get[1]);
$converted_amount = preg_replace("/[^0-9\.]/", null, $get[0]);
echo ceil($converted_amount);
?>
如何解决此错误?
答案 0 :(得分:2)
当我的脚本出错时,上述类型对我有用,但由于某种原因转换是错误的。似乎我需要做的就是更新脚本中的URL;我现在有以下内容(我一次只转换一种货币,但你应该能够找出适应方式!):
function convertCurrency($to){
$url = "http://finance.google.com/finance/converter?a=1&from=GBP&to=$to";
// Previously: $url = "http://www.google.com/finance/converter?a=1&from=GBP&to=$to";
$request = curl_init();
$timeOut = 0;
curl_setopt ($request, CURLOPT_URL, $url);
curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut);
$response = curl_exec($request);
curl_close($request);
$regularExpression = '#\<span class=bld\>(.+?)\<\/span\>#s';
preg_match($regularExpression, $response, $finalData);
$rate = $finalData[0];
$rate = strip_tags($rate);
$rate = substr($rate, 0, -4);
return $rate;
}
我希望这会有所帮助 ģ
答案 1 :(得分:1)
我遇到了同样的问题。我认为谷歌改变了输出结果的方式。 试试这个(适合我,今天下午12点14分CEST(UTC + 2)测试)
function convertCurrency($amount, $from, $to) {
$url = 'http://finance.google.com/finance/converter?a=' . $amount . '&from=' . $from . '&to=' . $to;
$data = file_get_contents($url);
preg_match_all("/<span class=bld>(.*)<\/span>/", $data, $converted);
$final = preg_replace("/[^0-9.]/", "", $converted[1][0]);
return round($final, 3);
}
echo convertCurrency(1, 'EUR', 'USD'); // output: 1.195
/* I got errors until i've changed this line:
$final = preg_replace("/[^0-9.]/", "", $converted[1]); to:
$final = preg_replace("/[^0-9.]/", "", $converted[1][0]);
.. maybe it works for your code too
*/
答案 2 :(得分:0)
试试这个
适合我。
将其更改为:
$url = "https://finance.google.com/bctzjpnsun/converter?a=$amount&from=$from_Currency&to=$to_Currency";