Categories: Development

Simple currency convert with API PHP

A free way to get currency conversion rates within in an api callback is api.fixer.io

https://api.fixer.io/latest?base=USD

Returns

{"base":"USD","date":"2017-11-20","rates":{"AUD":1.3235,"BGN":1.6601,"BRL":3.2585,"CAD":1.2788,"CHF":0.99109,"CNY":6.634,"CZK":21.703,"DKK":6.3164,"GBP":0.75494,"HKD":7.8122,"HRK":6.4212,"HUF":265.21,"IDR":13524.0,"ILS":3.5139,"INR":65.103,"JPY":112.13,"KRW":1095.9,"MXN":18.97,"MYR":4.1481,"NOK":8.2589,"NZD":1.4636,"PHP":50.727,"PLN":3.5915,"RON":3.9482,"RUB":59.542,"SEK":8.453,"SGD":1.3557,"THB":32.77,"TRY":3.9225,"ZAR":14.055,"EUR":0.84882}}

Now its about simply using a json decode inside a function that returns what we want:

function usdtoaud($usd) {
    $data = json_decode(file_get_contents('http://api.fixer.io/latest?base=USD'));
    $aud = $data->rates->AUD;
    $result = $usd * $aud;
    return $result;
}

If we go echo usdtoaud(10); it will return 13.235 meaning $10USD gets us $13.235 AUD. To reverse this and get AUD to USD:

function audtousd($aud) {
    $data = json_decode(file_get_contents('http://api.fixer.io/latest?base=AUD'));
    $usd = $data->rates->USD;
    $result = $aud * $usd;
    return $result;
}

You can also make conversions for all the available currencies in the api call, like EUR to USD or CAD to USD etc etc.

 

 

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago