需要即時匯率換算功能?本文示範如何使用 Yahoo Finance 非官方 API 獲取即時匯率,含 cURL 請求、錯誤處理與快取優化。
<?php
/**
* 獲取即時匯率
* @param string $from 來源貨幣代碼 (如 USD, TWD, JPY)
* @param string $to 目標貨幣代碼
* @return float|false 匯率或失敗回傳 false
*/
function getExchangeRate(string $from, string $to) {
$from = strtoupper($from);
$to = strtoupper($to);
// Yahoo Finance API 端點 (非官方,可能失效)
$url = "https://query1.finance.yahoo.com/v8/finance/chart/{$from}{$to}=X";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Exchange Bot)',
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($error || $httpCode !== 200) {
error_log("匯率 API 錯誤: HTTP $httpCode, $error");
return false;
}
$data = json_decode($response, true);
// 解析 Yahoo Finance 回應結構
try {
$rate = $data['chart']['result'][0]['meta']['regularMarketPrice'];
return (float) $rate;
} catch (Exception $e) {
error_log("匯率解析失敗: " . $e->getMessage());
return false;
}
}
// 使用範例
$rate = getExchangeRate('USD', 'TWD');
if ($rate) {
echo "1 USD = $rate TWD";
echo "100 USD = " . number_format(100 * $rate, 2) . " TWD";
} else {
echo "無法獲取匯率,請稍後再試";
}
?>
<?php
// 旧版 Yahoo CSV 介面 (已停用/不穩定)
function getExchangeRateLegacy($from, $to) {
$url = "https://download.finance.yahoo.com/d/quotes.csv?s={$from}{$to}=X&f=l1";
$rate = @file_get_contents($url);
return $rate !== false ? (float)trim($rate) : false;
}
?>
<?php
class ExchangeRateService {
private $cache_dir;
private $cache_ttl = 300; // 5 分鐘快取
private $providers = [
'yahoo' => 'https://query1.finance.yahoo.com/v8/finance/chart/%s%s=X',
'exchangerate_host' => 'https://api.exchangerate.host/latest?base=%s&symbols=%s',
'fixer' => 'https://data.fixer.io/api/latest?access_key=YOUR_KEY&base=%s&symbols=%s',
];
public function __construct($cache_dir = '/tmp/exchange_cache') {
$this->cache_dir = $cache_dir;
if (!is_dir($cache_dir)) mkdir($cache_dir, 0755, true);
}
public function getRate(string $from, string $to): ?float {
$cache_key = "{$from}_{$to}.json";
$cache_file = $this->cache_dir . '/' . $cache_key;
// 檢查快取
if (file_exists($cache_file) && (time() - filemtime($cache_file) < $this->cache_ttl)) {
$cached = json_decode(file_get_contents($cache_file), true);
if ($cached) return $cached['rate'];
}
// 嘗試多個提供者
foreach ($this->providers as $name => $url_template) {
$rate = $this->fetchFromProvider($name, sprintf($url_template, $from, $to));
if ($rate !== false) {
// 寫入快取
file_put_contents($cache_file, json_encode([
'rate' => $rate,
'provider' => $name,
'time' => time(),
]), LOCK_EX);
return $rate;
}
}
return null; // 所有來源都失敗
}
private function fetchFromProvider(string $name, string $url): ?float {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_USERAGENT => 'PHP ExchangeRateService/1.0',
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200 || !$response) return null;
$data = json_decode($response, true);
try {
switch ($name) {
case 'yahoo':
return (float)($data['chart']['result'][0]['meta']['regularMarketPrice'] ?? 0);
case 'exchangerate_host':
return (float)($data['rates'][$to] ?? 0);
case 'fixer':
return (float)($data['rates'][$to] ?? 0);
}
} catch (Exception $e) {
error_log("Provider $name parse error: " . $e->getMessage());
}
return null;
}
}
// 使用
$service = new ExchangeRateService();
$rate = $service->getRate('USD', 'TWD');
?>
<?php
// 簡單穩定的免費替代方案
$url = "https://api.exchangerate.host/latest?base=USD&symbols=TWD";
$data = json_decode(file_get_contents($url), true);
$rate = $data['rates']['TWD'] ?? null;
?>