Reputation: 1094
I am using google currency conversion API in php by using file_get_content but unable to get output because of getting error ,so how to convert any currency by using following API in Php.
<?php
function convertCurrency($amount, $from, $to)
{
$url = "http://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
$data = file_get_contents($url);
preg_match("/<span class=bld>(.*)<\/span>/",$data, $converted);
return $converted[1];
}
echo convertCurrency(1500, 'USD', 'INR');
?>
Getting error like this
Message: file_get_contents(http://www.google.com/finance/converter?a=1500&from=USD&to=INR): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
Upvotes: 1
Views: 17151
Reputation: 96
function thmx_currency_convert($amount){
$url = 'https://api.exchangerate-api.com/v4/latest/USD';
$json = file_get_contents($url);
$exp = json_decode($json);
$convert = $exp->rates->USD;
return $convert * $amount;
}
echo thmx_currency_convert(9);
Upvotes: 8
Reputation: 139
A Bit Late, but it might help Some One, As Benjamin said
You're not calling an actual API, you're scraping a web page, which means that:
- you're most likely violating Google's TOS
- you're more likely to get rate-limited (or be detected as abuse and be blacklisted) at some point if you're fetching this page too often
The Code Snippet
$url = "https://www.google.com/search?q=INR+to+USD";//Change Accordingly
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$data = explode("1 Indian Rupee = ",$result);//Change Accordingly
$one_inr_rate_to_usd = (float) substr($data[1],0,7);
Upvotes: 1
Reputation: 36554
I already answered a very similar question just a few days ago (the code was pretty much the same as yours).
I encourage you to read my answer:
You're not calling an actual API, you're scraping a web page, which means that:
- you're most likely violating Google's TOS
- you're more likely to get rate-limited (or be detected as abuse and be blacklisted) at some point if you're fetching this page too often
This is probably what you encountered here. You've most likely been blacklisted.
Solution: use a proper API such as OpenExchangeRates.
Upvotes: 0