1

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

Anonymous
  • 1,074
  • 3
  • 13
  • 37
  • it already says `403 Forbidden` , so no, you can't scrape it this way – Kevin Jun 19 '18 at 07:10
  • @Ghost so how to do this can you please give me suggestion how to solve this currency conversion in php – Anonymous Jun 19 '18 at 07:13
  • you can check out these answers here, https://stackoverflow.com/questions/3139879/how-do-i-get-currency-exchange-rates-via-an-api-such-as-google-finance – Kevin Jun 19 '18 at 07:37
  • try to check which of them fits your requirements – Kevin Jun 19 '18 at 07:37

3 Answers3

6
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);
1

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);
GuruCharan
  • 139
  • 1
  • 14
0

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.

Community
  • 1
  • 1
BenMorel
  • 34,448
  • 50
  • 182
  • 322