使用 PHP 进行货币兑换 [已关闭]

2022-08-30 19:09:54

我正在寻找一种方法,在网站上将任何金额从一种货币转换为另一种货币。用户将输入类似于“100”的内容并选择 USD 作为货币,然后选择澳大利亚或加拿大元作为要转换为的货币。当他点击“转换”按钮时,我想通过一些API自动转换该金额,并以他选择转换为的货币向他显示金额。

有什么想法吗?


答案 1

经过大量搜索,发现了这一点。

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

    // YOUR APPLICATION CODE HERE, e.g.
    $base_price = 12; // Your price in USD
    $EUR_price = round(($base_price * $response_object->rates->EUR), 2);

    }
    catch(Exception $e) {
        // Handle JSON parse error...
    }
}

这工作正常。代码段来自:https://www.exchangerate-api.com/docs/php-currency-api


答案 2

此方法使用Yahoo currency API完整教程:PHP,Python,Javascript和jQuery中的货币转换器

function currencyConverter($currency_from, $currency_to, $currency_input) {
    $yql_base_url = "http://query.yahooapis.com/v1/public/yql";
    $yql_query = 'select * from yahoo.finance.xchange where pair in ("' . $currency_from . $currency_to . '")';
    $yql_query_url = $yql_base_url . "?q=" . urlencode($yql_query);
    $yql_query_url .= "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
    $yql_session = curl_init($yql_query_url);
    curl_setopt($yql_session, CURLOPT_RETURNTRANSFER, true);
    $yqlexec = curl_exec($yql_session);
    $yql_json =  json_decode($yqlexec, true);
    $currency_output = (float) $currency_input * $yql_json['query']['results']['rate']['Rate'];

    return $currency_output;
}

$currency_input = 2;
//currency codes : http://en.wikipedia.org/wiki/ISO_4217
$currency_from = "USD";
$currency_to = "INR";
$currency = currencyConverter($currency_from, $currency_to, $currency_input);

echo $currency_input . ' ' . $currency_from . ' = ' . $currency . ' ' . $currency_to;

推荐