Search code examples
phpapicurrency

How to Convert Currency using google currency API in Php?


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


Solution

  • 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);