PHP 货币转换

 

使用以下代码,可以获取当天的汇率进行货币转换

function convert_currency($number, $currency) {
    // Fetching JSON
    $req_url = 'https://api.exchangerate-api.com/v4/latest/USD';
    $response_json = file_get_contents($req_url);
    // Continuing if we got a result
    if (false !== $response_json) {
        // Try/catch for json_decode operation
        try {
            // Decoding
            $response_object = json_decode($response_json);
            if (!property_exists($response_object->rates, $currency)) {
                return 0;
            }
            return round($number / $response_object->rates->$currency, 2);
        } 
        catch (Exception $e) {
            return 0;
        }
    }
}
echo convert_currency(100, "CNY");
posted @ 2020-01-20 16:07  Ryan_zheng  阅读(1777)  评论(3编辑  收藏  举报