Dylan Smith

A free exchange rate API using Google Search/Calculator

with 2 comments

I’ve been maintaining a small personal site for some time that requires an exchange rate service. Free exchange rate RSS feeds are quite hard to come by (but this one is quite good, and only requires attribution), so I wondered if it would be possible to use Google Finance to get exchange rates. As it turns out, it’s easier than that.

I often use Google Search to give me quick exchange rate calculations by typing “1 GBP in ZAR” into my Chrome URL bar, and Google Calculator does the rest. I did some searching and found this blog post where the author wrote a C# wrapper for Google Calculator to provide this functionality.

I need my wrapper in JavaScript, so I wrote one quickly, using jQuery. Note that Google Calculator returns an invalid JSON object (the object keys are not quoted), so I had to eval a fixed response (potentially unsafe) or just treat the response as a string and run some regex against it. Also, for numbers larger than 1000, Google returns spaces in the number, so you have to cater for whitespace as well.

function forex(val, from, to, callback) {
    $.ajax({
        url: 'http://www.google.com/ig/calculator?hl=en&q='+val+from+'%3D%3F'+to,
        type: 'GET',
        datatype: 'string',
        success: function(data) {
            var json = eval("(" + data+ ")"), output;
            if (typeof json == 'object' && json.rhs) {
                output = json.rhs.match(/[0-9.\s]+/ig);
                output = output[0] || false;
            } else {
                output = data.match(/[0-9.\s]+/ig);
                output = output[1] || false;
            }
            output = (output !== false) ? Number(output.replace(/\s/,'')) : output;
            callback(output);
        },
        error: function() {
            callback(false);
        }
    });
}

function output(data) {
    $('#output').html(data);   
}
    
forex(100, 'GBP', 'ZAR', output);

You can see it in action on JSFiddle.

Update:
I had to port this to PHP, so here is a PHP version as well:

private function convert($val, $from, $to) {
  $url = "http://www.google.com/ig/calculator?hl=en&q={$val}{$from}%3D%3F{$to}";
  $json = file_get_contents($url);
  if ($json) {
    // fix google's json mess
    $json = preg_replace('/([{,])([^"\'\:]+)\:/', '$1"$2":', $json);
    $data = json_decode($json);
    if ($data !== null) {
      preg_match('/[0-9.]+/i', $data->rhs, $matches);
      if ($matches && count($matches) === 1) {
        $val = (float) $matches[0];
        if (is_float($val)) {
          return $val;
        }
      }
    }
  }
  return false;
}

Advertisement

Written by Dylan

Jul 5, 2011 at 11:25 am

2 Responses

Subscribe to comments with RSS.

  1. This example dont work because same origin policy.
    If i am wrong can you provide details about it

    rafael

    Dec 11, 2011 at 8:24 am

    • Yes, you are right: Google has now disallowed using the service in this manner. However, Yahoo Finance can be used as an alternative, for example:

      'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'

      Dylan

      Dec 12, 2011 at 1:16 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.