Convert EURO to GBP (Sterling) using PHP

This is a guide on how to convert EURO to GBP Sterling using PHP. In this tutorial, we will retrieve the EURO exchange rates from an external API before converting our money into Sterling.

In the PHP code below, we convert €5.50 into GBP:

A drill-down of the code:

  1. We set the base currency to EUR, as the API that we’re using requires a base currency in order to respond with exchange rates. EUR is the default base currency for this API, but I’m setting it manually for the sake of clarity.
  2. In this example, we are using the API at api.fixer.io – Note that this is a free API and that the results are not in real time.
  3. We make a GET request to the API using PHP’s file_get_contents function.
  4. We check the return value of file_get_contents in order to make sure that the request was carried out successfully.
  5. We attempt to decode the exchange rates JSON into a PHP associative array using the function json_decode.
  6. If the return value of json_decode is not an array, then it is safe to say that something has gone wrong. For better error checking, check out our article on JSON error handling.
  7. We retrieve the EURO to GBP exchange rate from the associative array.
  8. In this example, I set the amount of EURO to 5.50. i.e. We want to convert €5.50 into Sterling.
  9. We use the formula: EURO x GBP rate.
  10. We var_dump out the result. In most cases, you’ll find that the result is a float value that has more than two decimal places (the fractional part).
  11. In order to “clean up” the result and round it to two decimal places, we output the GBP value using PHP’s number_format function.

Comments

comments