首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

已失效:Yahoo Finance 匯率 API 替代方案與現代 PHP 實作指南

     編輯:PHP 綜合知識

⚠️ 重要提醒: 原文使用的 download.finance.yahoo.com 介面已於 2017 年停止服務,以下提供現代、可維護的替代方案與最佳實踐代碼。

推薦替代資料源(免費額度)

服務免費額度特色註冊
exchangerate.host無限制、無需 Key開源、支援歷史匯率、CDN 快取不需
ExchangeRate-API1,500 req/月穩定、支援 HTTPS、Base 貨幣可調需
CurrencyLayer250 req/月企業級、SLA、支援加密貨幣需
Open Exchange Rates1,000 req/月歷史資料完整、SDK 豐富需

現代 PHP 實作:以 exchangerate.host 為例

1. 使用 HTTP Client(Guzzle / Symfony HttpClient / 原生 curl)

<?php
// composer require guzzlehttp/guzzle
use GuzzleHttp\Client;

function getExchangeRate(string $from, string $to, float $amount = 1.0): ?float
{
    $client = new Client([
        'base_uri' => 'https://api.exchangerate.host/',
        'timeout'  => 5.0,
    ]);

    try {
        $response = $client->get('convert', [
            'query' => [
                'from'   => strtoupper($from),
                'to'     => strtoupper($to),
                'amount' => $amount,
            ],
            'headers' => ['Accept' => 'application/json'],
        ]);

        $data = json_decode($response->getBody()->getContents(), true);
        return $data['result'] ?? null;
    } catch (Throwable $e) {
        // 記錄錯誤、拋出自訂例外或回傳 null
        error_log('匯率查詢失敗: ' . $e->getMessage());
        return null;
    }
}

// 使用範例
$rate = getExchangeRate('CNY', 'USD', 100);
echo "100 CNY ≈ {$rate} USD"; // 100 CNY ≈ 13.85 USD

2. 無依賴原生寫法(PHP 8.1+ file_get_contents + stream context)

<?php
function getRateNative(string $from, string $to): ?float
{
    $url = 'https://api.exchangerate.host/latest?base=' . urlencode($from) . '&symbols=' . urlencode($to);
    
    $ctx = stream_context_create([
        'http' => [
            'method'  => 'GET',
            'timeout' => 5,
            'header'  => 'Accept: application/json',
        ],
        'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
    ]);

    $json = @file_get_contents($url, false, $ctx);
    if ($json === false) return null;

    $data = json_decode($json, true);
    return $data['rates'][$to] ?? null;
}

生產環境必備:快取與容錯

匯率不需即時到毫秒級,建議快取 10–60 分鐘:

<?php
// 使用 Redis / APCu / 檔案快取
function getCachedRate(string $from, string $to): float
{
    $key = "fx:{$from}:{$to}";
    $cached = apcu_fetch($key);
    if ($cached !== false) return $cached;

    $rate = getExchangeRate($from, $to) ?? 0;
    if ($rate > 0) apcu_store($key, $rate, 1800); // 30 分鐘
    return $rate;
}

並實作 Circuit Breaker、Fallback(如使用上一筆成功匯率)避免上游失效導致服務雪崩。

常見貨幣代碼對照(ISO 4217)

  • CNY:人民幣
  • USD:美元
  • EUR:歐元
  • JPY:日圓
  • HKD:港幣
  • TWD:新台幣

總結

  1. 棄用已停止的 Yahoo 介面,改用 exchangerate.host 或其他現代 API。
  2. 採用 HTTPS + JSON,搭配 Guzzle 或原生 HTTP Client。
  3. 務必加入 快取層 降低延遲與上游壓力。
  4. 實作 例外處理與 Fallback 保證服務可用性。

以此現代化架構替換舊代碼,即可獲得穩定、安全、可擴展的匯率轉換服務。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved