PHP - Currency Converter

From Global Programming Syntax

Jump to: navigation, search
YOU MAY USE THIS FUNCTION AT YOUR OWN RISK.

ALTHOUGH IT WORKS I AM NOT RESPONSIBLE OF ANY LEGAL
MATTERS YOU MAY RUN INTO BY USING THIS SCRIPT.

In some sites you may need to convert between currencies for payments or even budgets. Well it is almost impossible to keep a fully up to date record of all the required currencies on your server and their conversion rate but it is possible to use another websites currency converter on your website with a simple php script. First the function to use the yahoo currency converter is as follows:

function currency_convert($Amount,$currencyfrom,$currencyto)
{
$buffer=file_get_contents('http://finance.yahoo.com/currency-converter');
preg_match_all('/name=(\"|\')conversion-date(\"|\') value=(\"|\')(.*)(\"|\')>/i',$buffer,$match);
$date=preg_replace('/name=(\"|\')conversion-date(\"|\') value=(\"|\')(.*)(\"|\')>/i','$4',$match[0][0]);
unset($buffer);
unset($match);
$buffer=file_get_contents('http://finance.yahoo.com/currency/converter-results/'.$date.'/'.$Amount.'-'.strtolower($currencyfrom).'-to-'.strtolower($currencyto).'.html');
preg_match_all('/<span class=\"converted-result\">(.*)<\/span>/i',$buffer,$match);
$match[0]=preg_replace('/<span class=\"converted-result\">(.*)<\/span>/i','$1',$match[0]);
unset ($buffer);
return $match[0][0];
}

The above script will allow you to enter in an amount, the currency to convert from and currency to convert to. However you must use abbreviations for the currency names in this function. The abbreviations for converting from and to are as follows:

-------------
CONVERT FROM:
-------------

British Pound         GBP
Euro                  EUR
US Dollar             USD
Japanese Yen          JPY
Chinese Yuan          CNY
Australian Dollar     AUD
Swiss Franc           CHF
Canadian Dollar       CAD
Thai Baht             THB
Indian Rupee          INR
Indonesian Rupiah     IDR
Hong Kong Dollar      HKD


-----------
CONVERT TO:
-----------

Euro                  EUR
British Pound         GBP
US Dollar             USD
Japanese Yen          JPY
Chinese Yuan          CNY
Australian Dollar     AUD
Swiss Franc           CHF
Canadian Dollar       CAD
Thai Baht             THB
Indian Rupee          INR
Indonesian Rupiah     IDR
Hong Kong Dollar      HKD

And so an example of the usage of this script is as follows:

echo currency_convert(150.5,'GBP','USD');
Personal tools
languages
page stats
Toolbox