I was looking for a free / public API in which I could query a currency conversion rate just once per day, so no need for a large volume of requests. All of the major API’s looked great and offered a basic free account, however, none allowed one to specify the base rate, which made them useless, unless going for the paid option.
After almost giving up, I stumbled across the below free service, that suited my requirements and was very simple to use:
https://free.currencyconverterapi.com/
Now that I have a viable API to use, it was time to knock together a PHP script which would return a conversion rate for use in the larger application.
The JSON Get Function
Firstly, here is the JSON PHP function which uses CURL to return arrays from API’s. I have used a bunch of times and found it very helpful.
function jsonget($url, $headers) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => $headers
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
return $response;
}
}
You could place this function into an includes file for reuse throughout your web app. Next, lets use the function to make a query of the API.
Returning the Currency Conversion Rate
Now, running the code is fairly straight forward in a few lines:
// Set URL, no headers are required $currencyconv_url = "http://free.currencyconverterapi.com/api/v5/convert?q=AUD_NZD&compact=y"; // Run function and return results $currencyconv = jsonget($currencyconv_url, $currencyconv_headers); $currencyconv_details = json_decode($currencyconv, true); // Pull the currency rate out of the array $nz_currency_rate = $currencyconv_details['AUD_NZD']['val']; echo $nz_currency_rate;
You might notice from the above code that the currencies are both set in the url variable, in the ?q= parameter using their 3 character abbreviations such as AUD and NZD.
If you wanted use a different currencies, there are just two places need to make the change, basically the first and last variables. So the AUD_NZD will become AUD_USD like below:
// Set URL, no headers are required $currencyconv_url = "http://free.currencyconverterapi.com/api/v5/convert?q=AUD_USD&compact=y"; // Run function and return results $currencyconv = jsonget($currencyconv_url, $currencyconv_headers); $currencyconv_details = json_decode($currencyconv, true); // Pull the currency rate out of the array $usd_currency_rate = $currencyconv_details['AUD_USD']['val']; echo $usd_currency_rate;
I hope this helps someone 🙂