Friday 4 March 2016

How to Convert Currency using Google Finance in PHP



In this post I covered how to convert currency using Google Finance in PHP. Convert currency on live rate is big issue in e-commerce website. But Google has solved this issue. It allow us to use it's currency converter calculator on it official website. We have just pass three parameter like amount, from currency and to currency using http request to it's site on it site it calculate currency amount on live rate. We can use file_get_content() function and fetch converted amount back to our webpage. So, This is very useful tutorial. I hope you will learn something from this tutorial.


Source Code

currency_converter.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', 'CNY');  
 ?>  

3 comments:

  1. Warning: file_get_contents(http://www.google.com/finance/converter?a=1500&from=USD&to=CNY): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in D:\wamp\www\currency_converter.php on line 5


    uri doesn't exists by google

    ReplyDelete
    Replies
    1. Right

      Warning: file_get_contents(http://www.google.com/finance/converter?a=1500&from=USD&to=CNY): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in C:\xampp\htdocs\mylocaltest\index.php on line 5

      Notice: Undefined offset: 1 in C:\xampp\htdocs\mylocaltest\index.php on line 7

      Delete