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:

<?php

//We set EUR as our base currency.
$baseCurrency = 'EUR';

//The API URL for our EURO to foreign currency exchange rates.
$apiUrl = "http://api.fixer.io/latest?base=$baseCurrency";

//Make the API call.
$content = file_get_contents($apiUrl);

//Make sure that the API call was successful before continuing.
if($content === false){
    throw new Exception('Unable to connect to API.');
}

//Decode the currency rates from JSON into an associative array.
$currencyRates = json_decode($content, true);

//Make sure that the JSON is valid before continuing.
if(!is_array($currencyRates)){
    throw new Exception('Unable to decode JSON.');
}

//In this case, we want the EURO to GBP exchange rate.
$gbpRate = $currencyRates['rates']['GBP'];

//For this example, we are converting 5.50 EUR into Sterling.
$euros = 5.50;

//To get the Sterling amount, simply multiply our EURO by the GBP exchange rate.
$gbp = $euros * $gbpRate;

//var_dump our float value for example purposes.
var_dump($gbp);

//Print out the end result using PHP's number_format function.
echo number_format($gbp, 2);

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.