Long, long time ago, in a galaxy far, far away 🙂 I was searching for a way to get the exchange rate automatically and use it in a project I was working on back then. And, following the will of the Force, I’ve came up with this script, which queries Google for the exchange rate and parses the answer page with regular expressions.

The script has proven useful to a lot of people, but, several days ago, an user called Lars Sorhus posted a comment in which he posted a link to another Google service, that outputs a (malformed) JSON containing the exchange rate.

The JSON based solution is much more elegant than parsing a HTML file with regular expressions, so I went for it, but since Google’s conversion service doesn’t output well formatted json, PHP’s built-in json_decode() function won’t work, so I had to look for another parser.

I’ve settled for PEAR’s Services_JSON class for decoding the JSON, as the test said that it can parse almost anything. And it does. Here’s is an working example:

It uses exception, because I think that the OOP exceptions based approach is much better than return false or adding a passed by reference parameter to be used for error signaling. It’s very simple to use:

PHP

1

2

3

4

5

6

7

8

try{

$rate=exchangeRate(1,'euro','usd');

echo'Exchange rate is: '.$rate;

}

catch(Exception$exception){

// log $exception-&gt;getMessage()

echo'Due to technical difficulties, we couldn'tget the exchange rate';

}

Of course, you must include the Services_JSON.php class from the PEAR repository prior to calling exchangeRate().