Reputation: 1363
I'm attempting to build a currency converter function in PHP.
I have all my rates cached in a JSON file. (https://raw.github.com/currencybot/open-exchange-rates/master/latest.json)
My script takes GET values from the URL like so:
.com?amnt=10&from=USD&to=GBP
I've accessed the rates from those values like so:
$string = file_get_contents("cache/latest.json");
$jsonRates = json_decode($string, true);
foreach ($jsonRates as $rates => $rate) {
$fromRate = $rate[$from];
$toRate = $rate[$to];
}
Now I'm stuck. I have everything I need, I just have no idea what to do with it. How do I convert the $amnt variable from USD to GBP in this particular scenario.
Thanks!
Upvotes: 0
Views: 869
Reputation: 1886
You're looking for something like this, but this only works FROM USD.
$string = file_get_contents("cache/latest.json");
$jsonRates = json_decode($string, true);
foreach ($jsonRates["rates"] as $currency => $rate) {
if($currency==$_GET["to"]) {
echo $_GET["amnt"] * $rate;
break;
}
}
Try this to do all conversions:
echo number_format(($_GET["amnt"]/$jsonRates["rates"][$_GET["from"]])*$jsonRates["rates"][$_GET["to"]],3);
Upvotes: 2