Monday, June 22, 2009

PHP- Google Currency Converter - Convert variable amounts between currencies with a little help from our friend Google.

<?php

function Google_Currency($amount, $from, $to)
{
$matches = array();

if (
preg_match('~<b>.+? = (.+?)</b></h2>~', file_get_contents('http://www.google.com/search?q=' . urlencode(floatval($amount) . ' ' . strtoupper($from) . ' to ' . strtoupper($to))), $matches) > 0)
{
if (
array_key_exists(1, $matches) === true)
{
return
floatval($matches[1]);
}
}

return
false;
}
?>





Usage:

<?php
Google_Currency
(1, 'USD', 'EUR'); // 0.768816791
Google_Currency(1, 'USD', 'GBP'); // 0.686671702
Google_Currency(1, 'EUR', 'USD'); // 1.3007
Google_Currency(1, 'EUR', 'GBP'); // 0.893153883
Google_Currency(1, 'GBP', 'USD'); // 1.4563
Google_Currency(1, 'GBP', 'EUR'); // 1.11962789
?>

No comments: