PHP Currency converter tutorial

→ Are you a new visitor? Please visit the page guidance for new visitors ←

PHP Currency converter tutorial

This post will be a php currency converter tutorial where I’ll be showing you what I did in a few minutes based on the XML received directly from ECB (European Central Bank). The idea itself is simple and can be used in any projects you own / have. It can of course be developed further but this is just the basics for now. Ok, so lets get started, right?

PHP XML parsing

First we need to make sure we have our own XML file, it can be a link or a local file, but you need to make sure is public / have access to reading it.

For parsing our little XML file, we will use SimpleXML extension from PHP. It is really simple, see below:

In the above example we will read the “time” attribute for printing the current date of the currency. The output for this will be:

So basically that’s how you can get a value from the XML file.

Build get_rate() currency function

This function is really important, our XML file has its base currency in Euro, so we need to read our FROM and TO currency for conversion. You’ll understand this further in the second function. For now, below is a code snippet of the get_rate() function:

As you can see, we first use global $array_currency for us to pass to our function the $array_currency objects. Afterwards we count the objects and parse the array object. In case the currency does not exist, unfortunately the XML file I’m using does not have all currencies used with all countries, we will set a custom $rate of 99999999. This is just for using it further in our next function for testing / checking.

Build currency converter function

This here is the actual currency converter. It makes uses of the first function get_rate() for when it needs to change the base currency, or rather, the default FROM currency.

Basically since our XML file already has a rate with FROM base currency Euro, we check if the base currency is EUR, else we proceed further and get the two rates FROM and TO currencies.

The precision of this currency converter is made with 4 decimals, while using PHP_ROUND_HALF_EVEN.

Running the currency conversion

Lastly you just need to call the currency convert function and you are done:

Output will look similar to:

For those looking for the end code, they can use below snippet:

That’s it for now, happy coding!

Request an article ←