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");


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM