使用存储在JSON文件中的汇率进行货币转换


currency convert using rates stored in a JSON file

我正在尝试在PHP中构建一个货币转换器函数。

我有我所有的速率缓存在一个JSON文件。(https://raw.github.com/currencybot/open-exchange-rates/master/latest.json)

我的脚本从URL中获取GET值,如下所示:

com ? amnt = 10,从= USD& =

英镑

我已经从这些值中访问了速率,像这样:

    $string = file_get_contents("cache/latest.json");
    $jsonRates = json_decode($string, true);
    foreach ($jsonRates as $rates => $rate) {
        $fromRate = $rate[$from];
        $toRate = $rate[$to];
    }   

现在我被卡住了。我需要的东西都有了,只是不知道该怎么用。在这个特定的场景中,我如何将$amnt变量从美元转换为英镑?

谢谢!

你正在寻找这样的东西,但这只适用于美元。

    $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;
        }
    }

尝试执行所有转换:

echo number_format(($_GET["amnt"]/$jsonRates["rates"][$_GET["from"]])*$jsonRates["rates"][$_GET["to"]],3);