TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   General (http://www.talkphp.com/general/)
-   -   Creating a Simple Currency Converter with Automatic Symbols (http://www.talkphp.com/general/1422-creating-simple-currency-converter-automatic-symbols.html)

Wildhoney 11-09-2007 03:30 PM

Creating a Simple Currency Converter with Automatic Symbols
 
1 Attachment(s)
If you're from the UK then you'll appreciate this preface. If you're not then don't worry because I'll be doing the script from a USD perspective to satisfy the majority! Today we'll be making a currency converter, and as is common on Blue Peter, I'll be throwing bits of code at you like - here's one I made earlier! Basically what we'll be creating is a converter that automatically prepends the currency symbol to the front of the value and then works out the value in the currency that we specify.

We're going to begin this article with three nice defines. These defines will represent three different locales: Canada, Germany and Great Britain. There's no need at all to specify the United States because we will be converting from the USD to other currencies. Don't worry though, I will also be teaching you how to convert from another to currency to the USD with one or two amendments.

PHP Code:

define('CURRENCY_CAD''english-can');
define('CURRENCY_EUR''german');
define('CURRENCY_GBP''english-uk'); 

A comprehensive list of county codes can be found in the ISO 639 document and Microsoft MSDN also has a page on it. As my developer machine is on Windows, I will be using Windows for these but adding and editing language codes is rather simple. Unix even seems to support the above language codes when I tested the script.

All that these defines specify are the language codes to be used for various currencies which will allow us to automatically procure the currency symbol later on in our script. Once we have set out our series of defines for our supported currencies, we can begin with our function. I hope nobody has any problems with me calling the function get_currency. Seems logical! We're going to give it two arguments: one to specify the amount to convert and a second to set the particular currency we wish to convert to:

PHP Code:

function get_currency($iPrice$szLocale

Now what we have to do is configure the exchange rates that we wish to use. We are going to tell the script how much we can get for 1 precious US Dollar (USD). I will be using XE.com's Universal Currency Converter to calculate how much we can get for 1 dollar in the 3 currencies we are supporting: CDN, EUR and GBP. Once we have this information we can construct our array inside our function. Technically, you can construct the array outside of the function and then simply make it global, if you wish to.

PHP Code:

$aExchangeRates = array    (    
                            
'CAD' => 0.919996,
                            
'EUR' => 0.681642,
                            
'GBP' => 0.475255
                        
); 

Whether you know it or not, we now have all the information to begin with the core of the function. This will be where we procure the currency's symbol and then calculate the amount based on the exchange rates we specified from XE.com.

PHP Code:

setlocale(LC_MONETARY$szLocale);
$aLocale localeconv(); 

First we set locale to the region we wish to convert the USD amount to. These are located in the three defines at the beginning of our script. As we only need the monetary side of things, we explicitly tell PHP to change only that - this is done via the LC_MONETARY constant. Once we have changed the monetary locale to our desired location, we can acquire the currency's information - items such as its symbol ($, €, £, etc.) and international symbol (USD, EUR, GBP, etc.). We can use the international symbol to automatically obtain the conversion rate from our array that we constructed earlier. This is done like so:

PHP Code:

$iExchangeRate $aExchangeRates[trim($aLocale['int_curr_symbol'])]; 

With the above line we have obtained the current exchange rate that we input into our array. The next line is the heart of the conversion which is a simple mathematical multiplication:

PHP Code:

$iTotal $iPrice $iExchangeRate

There's really nothing that needs explaining in the above. We've simply multiplied the USD amount we fed into the function by the amount of the target currency you can get for 1 dollar. All we do then is return the amount and prepend the target currency's symbol:

PHP Code:

return $aLocale['currency_symbol'] . round($iTotal2); 

We have also used the round function to round the number 2 decimal places - which is how you will see almost every currency around the world formatted.

Now that we have completed our fairly straightforward function, we can make a call to it and let it convert an amount of 50 USD into, let's say, GBP:

PHP Code:

echo get_currency(50CURRENCY_GBP); 

Our function then returns the converted amount and we echo it out:

Quote:

£23.76
As you can see our function has cleverly deduced that $50 USD in GBP comes to £23.76. You can see that it's even prepended the correct currency symbol for us! How handy is that?

If you're not from the United States and wish to convert from, for example, GBP to the USD, then all you have to do is change one or two things as aforementioned. We first add a new define to the top of our page, like so:

PHP Code:

define('CURRENCY_USD''american-english'); 

We then also add to our array how many US dollars we can get for 1 Great British pound using XE.com, again. XE tells us you can get 2.10260 and as I have no reason to argue with that, we'll drop it straight into our array:

PHP Code:

$aExchangeRates = array    (    
                            
'CAD' => 0.919996,
                            
'EUR' => 0.681642,
                            
'GBP' => 0.475255,
                            
'USD' => 2.10260
                        
); 

If we were then to change our function call to specify the target currency as USD, and if you remember rightly we do that like this:

PHP Code:

echo get_currency(50CURRENCY_USD); 

Now when we run that code it will correctly tell us that £50.00 GBP equals $105.13 USD. I'm sure you're beginning to see how so flexible and beautiful our currency converter function is! I do hope that you've also learned a few things along the way. Please see the attached document for the full function.

Nor 11-11-2007 09:23 AM

This is a good post :), I dugg it, to be correct are you adam on digg :D?

Wildhoney 11-11-2007 01:34 PM

That be me :) !

Andrew 11-11-2007 04:40 PM

Very nice tutorial there Adam. :)

Germanium 11-12-2007 05:52 AM

excellent tutorial! was looking for something exactly like this.

__________________
Save YouTube Videos

Wildhoney 11-30-2007 01:08 PM

I'm glad you liked it, Germanium :-) I do hope you stick with us here at TalkPHP!

bdm 11-30-2007 01:10 PM

I don't need this now, but could see this being useful in the future.

Thanks! ;)

soup 01-11-2008 01:08 AM

Warning
 
This relies on the locales being set on the server

The "locale" always depends on the server configuration.

which to be honest is totally unecesary in this script with just 4 currencies.

steveNO 09-21-2009 11:49 AM

this looks good - but it seems static? or can you automatically grab the latest conversion rates on a daily basis?

bedex78 12-01-2009 11:47 PM

Yes, I would also like to know how we can automatically grab the latest conversion rates on a daily basis... Is this possible? Is there any sites that provides the data for free?

delayedinsanity 12-02-2009 12:20 AM

A quick search turned up this site; http://rss.timegenie.com/foreign_exchange_rates_forex

There's probably more like it, try google 'exchange rates (xml|feed|api)'

womers 03-16-2010 05:22 PM

Easy and Free Currency Converter API for PHP
 
Hey, I found a free and really easy PHP exchange rate converter at www.exchangerate-api.com , it's really easy to use, and is reliable (have been using it for the past year and no glitches) Some example code can be seen at www.exchangerate-api.com/php .


All times are GMT. The time now is 09:39 PM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0