Currency conversion using php and Google calculator api

Update 2:

As of November 1 2013, Google has discontinued iGoogle and hence this method no longer works. Please use the following free API instead :
www.dynamicguru.com/javascript/currency-conversion-using-javascript-and-openexchangerates-json-api/

Also check out our online currency conversion tool that uses the aforementioned JSON API :
http://dynamicguru.com/currency-converter/

While most of us use Google for searching the web for information , few are aware that it has an inbuilt calculator which can also be used for converting a currency into another . Doing so is really simple , you just type ” AMOUNT CURRENCY_CONVERTING_FROM in CURRENCY_CONVERTING_TO ” and search , the inbuilt calculator will give you the result .For example , if one wants to convert 1 U.S Dollar into Euro , he shall type “1 USD in EUR” .

Now lets get to the topic of this post , Google also has a secret calculator API ( http://www.google.com/ig/calculator ) that is usually used for iGoogle gadgets , but since its free and open , anyone can use it .

So if you want to convert a currency into another using the API , your callback URL would look like :

www.google.com/ig/calculator?hl=en&q=AMOUNT-FROM_CURRENCY=?TO_CURRENCY
// 1 USD in EUR example
www.google.com/ig/calculator?hl=en&q=1USD=?EUR

In the above example , you get a string which looks like "{lhs: "1 U.S. dollar",rhs: "0.838574423 Euros",error: "",icc: true}" . You can easily explode() the string using php and extract the required data .

To make things easier for you , here is a simple php function that converts a currency into another using the Google calculator API . This example uses cURL , so you have to have it enabled for this code to work .

<?php

function currency($from_Currency,$to_Currency,$amount) {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
$data = explode(' ', $data['3']);
$var = $data['0'];
return round($var,3);
}

?>

The value returned by Google usually has 9 decimal places , you can round it off to a no. of digits after decimal of you choice using the round() function . By default the above function rounds the value to 3 digits after decimal .

Now here is how you can use the function in your scripts

<?php 

//This will display current value of 1 USD in INR ( Indian Rupees )
echo currency("USD","INR",1); 

?>

Hope this has helped you with converting currencies using php on your website
You can view a working example of the above code at Malegaon Online .

Admin

I am a student of Computer Engineering and a freelance web designer and developer with a passion for interface design. WordPress is my framework of choice and I also build web and mobile applications. My Google+ Profile

26 responses to this entry

  • Convert currency using Google API calculator 7th Sep '10 at 3:06 pm

    [...] was found on Dynamic Guru website, and was improved by [...]

  • isnt the response simply a json?

    so would be easier to just perform a json_decode rather than exploding the data (esspecially with whitespace) which doesnt work in all cases as i just found out after trialing your function – it is helpful none the less :) just use json_decode in place of the exploding ;)

    thanks,

    Reply / Quote
  • json_decode won’t work cause the returned data is JavaScript object string.

    The difference between JavaScript object and JSON is that with JSON the variable name foo is enclosed in double quotes. json_decode doesn’t work with JavaScript object strings.

    Reply / Quote
  • // the following strings are valid JavaScript but not valid JSON

    // the name and value must be enclosed in double quotes
    // single quotes are not valid
    $bad_json = “{ ‘bar’: ‘baz’ }”;
    json_decode($bad_json); // null

    // the name must be enclosed in double quotes
    $bad_json = ‘{ bar: “baz” }’;
    json_decode($bad_json); // null

    // trailing commas are not allowed
    $bad_json = ‘{ bar: “baz”, }’;
    json_decode($bad_json); // null

    Reply / Quote
  • Unless I’m mistaken, Google’s response is not valid JSON, because the keys are not enclosed in double quotes.

    Reply / Quote
  • @Simon That is not a valid JSON format. The keys are not enclosed in quotes.

    Reply / Quote
  • Google calculat | Miranda1929 31st Mar '12 at 8:21 am

    [...] Currency conversion using php and Google calculator api – Dynamic …Jun 9, 2010 … Google is a wonderful ! While most of us use it for searching the web for information , few are aware that it has an inbuilt calculator which can … [...]

  • $data = str_replace(‘rhs:’, ‘”rhs”:’, $data);
    $data = str_replace(‘lhs:’, ‘”lhs”:’, $data);
    $data = str_replace(‘error:’, ‘”error”:’, $data);
    $data = str_replace(‘icc:’, ‘”icc”:’, $data);
    $data = json_decode($data, true);

    This seems to work ok for me…

    Reply / Quote
  • $json = json_decode(preg_replace(array(‘/(\w+):/’, ‘/\//’), array(‘”$1″:’, ‘\/’), $str));

    this one-liner does it all

    Reply / Quote
  • Weather forecast script in php using Google Weather API | Dynamic Guru 7th Oct '12 at 10:57 am

    [...] few days back , we published an article about currency conversion using Google calculator API and php. Today we are going to show you how to display current weather information and forecast data using [...]

  • how to get currency symboles instead of currency names

    Reply / Quote
  • Sir you have done the great job……………….

    Reply / Quote
  • Thank you! You saved my ass! :D

    Reply / Quote
  • Soon I will publish an fix for this code… I made it to fix the response to proper JSON structure… just filter the $rawdata like:


    if(preg_match('/[a-z0-9]{1,25}:/i',$rawdata)){
    $rawdata = str_replace("'",'"',preg_replace('/([a-z0-9]{1,25})(:)/s','"$1":',$rawdata));
    }

    $json = json_decode($rawdata);
    $this->echo_array($json);

    $data = explode('_', $json->rhs);
    $var = $data['0'];

    This will allow you to use json_decode function.

    Reply / Quote
  • you done good work………….

    Reply / Quote
  • This method doesn’t work for output bigger than 999.99 because it put spaces between numbers :

    http://www.google.com/ig/calculator?hl=en&q=5000USD=?EUR

    Return

    {lhs: “5000 U.S. dollars”,rhs: “3 838.18224 Euros”,error: “”,icc: true}

    And the php script will give you 3 !!!!

    Reply / Quote
    • This is a better way to do it :

      function currency($from_Currency, $to_Currency, $amount)
      {
      $from_Currency = urlencode($from_Currency);
      $to_Currency = urlencode($to_Currency);
      $url = “http://www.google.com/ig/calculator?hl=en&q=1$from_Currency=?$to_Currency”;
      $ch = curl_init();
      $timeout = 0;
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_USERAGENT, ‘Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)’);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
      $rawdata = curl_exec($ch);
      curl_close($ch);
      $data = explode(‘”‘, $rawdata);
      $data = explode(‘ ‘, $data['3']);
      $var = $data['0']*$amount;
      return round($var, 3);
      }

      Reply / Quote
  • This function work well for me, until Nov 5, 2013. Google has closed down iGoogle.
    Anyone has another function that works?

    Reply / Quote
  • i am using http://www.google.com/ig/calculator?hl=en&q=1$from_Currency=?$to_Currency .. this script but not working any more … .

    Why … .

    Please give me reason and Solution for that …

    Reply / Quote
    • here same problem..
      this is not working….

      function currency($from_Currency,$to_Currency,$amount) {
      $amount = urlencode($amount);
      $from_Currency = urlencode($from_Currency);
      $to_Currency = urlencode($to_Currency);
      $url = “http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency”;
      $ch = curl_init();
      $timeout = 0;
      curl_setopt ($ch, CURLOPT_URL, $url);
      curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_USERAGENT , “Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)”);
      curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
      $rawdata = curl_exec($ch);
      curl_close($ch);
      $data = explode(‘”‘, $rawdata);
      $data = explode(‘”‘, $data['3']);
      $var = $data[0];
      return round($var,3);
      }

      Reply / Quote
  • As of Nov 1, 2013 Google shutdown Igoogle (ig). Unfortunately, The code/API became obsolete.

    Reply / Quote
  • Hello

    When i am convert amount in 10 INR to USD then giving ouput

    10 Gws-header =

    not convert properly. plz any one suggest me what i do now?
    i want help from you

    Reply / Quote
  • this is bad for me…
    if any other script availabe please send me

    Reply / Quote
  • Favoriti | Daniele Milana 14th Nov '13 at 9:13 pm

    [...] http://www.google.com/ig/api?stock=YHOO Create A Weather Application With Google API Using PHP Currency conversion using php and Google calculator api – Dynamic Guru http://www.google.com/ig/api?movies=perugia http://www.google.co.in/ig/api?news&hl=it i Google's Secret [...]

  • Can I Implement This Code In My Site For Commercial Use ?

    Reply / Quote

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2014 All rights reserved | Powered by WordPress
Back to top ↑
Theme by dynamicguru.com