Usage

First 3 parameters are required. First one is the origin currency and the second one is target currency.

First 2 parameters should be the same type. If you are doing a county code based conversion both must be country codes. If you are doing currency code based conversion, both should be currency codes.

3rd parameter is the amount you want to be converted. Should be decimal digits without any currency signs or codes attached to it.

4th parameter is optional and set as true by default. When enabled function will prepend or append the currency sign (or code) to the output amount. You may want to turn that off if you will use the returned amount in a calculation.

5th and the last parameter is calculation precision. Controls the number of digits after the decimal point. Default is 5.

Usage Samples

currency_convert(“EUR”,”USD”,100)

currency_convert(“FR”,”GB”,98);

currency_convert(“AUD”,”CNY”,145,false,8);

currency_convert(“GR”,”DK”,3500,true,2);

Download

License

This code is free to use, distribute, modify and study. When referencing please link back to this website / post in any way e.g. direct link, credits etc. If you find this useful, please leave a comment and share using the buttons below!

Hallo :) I just wanted to thank you for your snippet. really useful indeed :) Since I had to call your function several times on a webpage, I thought that maybe I could call only once the BCE xml. So I slightly changed your snippet as follows, and I hope it can be useful to you :) Thank you very much :) s@ch@x

/* what I did is to take out $XMLContent and added a $ratesRequested. Both variables where latere referenced into your function with the “global” keyword. that’s it. this way the xml is requested only once. In my case was a speedup in performance. Once the site is online, I will add any credit you prefer to it. thank you ;) */

if ($in && $out) {//Both currencies available, continue if ( !$ratesRequested ) // we check if the XML was parsed, in case it is, we skip this step – s@ch@x { //Load live conversion rates and set as an array $XMLContent= file(“http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml”); if(is_array($XMLContent)) { foreach ($XMLContent as $line) { if (ereg(“currency='([[:alpha:]]+)'”,$line,$currencyCode)) { if (ereg(“rate='([[:graph:]]+)'”,$line,$rate)) { $RATES[$currencyCode[1]]=$rate[1]; } } } } $ratesRequested = true; // in case we are parsing the XML from BCE, we set this to true, so that we wont parse it again – s@ch@x } if(is_array($RATES)) { $RATES[“EUR”]=1; //Add EUR reference to array if ($in!=”EUR”) {//Normalize rate to given input $BASE=$RATES[$in]; foreach ($RATES as $code => $rate) { $RATES[$code]=round($rate/$BASE,$sensitivity); } }