I was looking for a way to include a currency converter in a website. Not wanting to reinvent the wheel, I googled around for a PHP currency conversion tool, but I didn’t find anything suitable. They were bloated, filled with annoying copyright notices with lots of logos or you had to include a file from their server. In other words, only crap. I needed something simple. You know…get in, score, get out.

Exchange Rate function

So I’ve wrote a small PHP function, that queries Google for the current exchange rate. It works okay and it’s reasonably fast, depending on the server’s bandwidth. Of course, I’m talking about the server on with the script runs, not Google’s servers, because those are fast enough to fulfill every porn addict’s wildest dreams.

The function is quite easy to use, as you can see in the following example:

require( '/path/to/exchange_rate.php' );
echo '100 euro equals ' . exchangeRate( 100, 'euro', 'usd' ) . ' US Dollars and ' . exchangeRate( 100, 'euro', 'canadian dollars' ) . ' Canadian Dollars';

The first parameter is the amount, the second one is the currency in which the amount is expressed in, and the third one is the currency in which you want to make the exchange. Since Google’s algorithms are very reliable, currencies’ names can be expressed in many ways. For example, the function will work with any of “usd”, “us dollars”, “united states dollars”, and so on. If the query fails, the function will simply return false.

Source code and disclaimer

Here it is:

/**
 * queries Google for the current exchange rate, doesn't need cURL
 *
 * @param mixed  $amount
 * @param string $currency
 * @param string $exchangeIn
 * @return mixed
 * @author Tudor Barbu
 * @copyright MIT
 */
function exchangeRate( $amount, $currency, $exchangeIn )
{
    $googleQuery = $amount . ' ' . $currency . ' in ' . $exchangeIn;
    $googleQuery = urlEncode( $googleQuery );
    $askGoogle = file_get_contents( 'http://www.google.com/search?q=' . $googleQuery );
    $askGoogle = strip_tags( $askGoogle );
    $matches = array();
    preg_match( '/= (([0-9]|\.|,|\ )*)/', $askGoogle, $matches );
    return $matches[1] ? $matches[1] : false;
}

echo exchangeRate( 1000, 'euro', 'dollars' );

But keep in mind that if Google changes the way currency conversion queries are displayed, this function might not work properly, or, depending on your luck, might not work at all. Also, it would be best if you’d read Google’s Currency Conversion Disclaimer before using this function.

Later edit

See this comment for an improved version of the script made by the user Manic.
Even later edit: check out this script: Better PHP Exchange rate. It’s much better :P