萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 串接中國天氣網 API 實作即時天氣顯示:伺服器端代理 + 前端 AJAX 載入

中國天氣網提供免費的即時天氣 API,回傳 JSON 格式資料。為解決跨域與 HTTPS 混合內容問題,採用「PHP 伺服器端代理 + 前端 AJAX 載入」架構,完整示範從資料獲取到頁面渲染的全流程。

架構圖解

瀏覽器 --AJAX--> weather.php (PHP 代理) --cURL--> weather.com.cn
     ▲                                                      │
     └──────────────── JSON 回傳 ◄──────────────────────────┘

後端代理程式 (weather.php)

<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *'); // 允許跨域,生產環境請限制具體域名
header('Cache-Control: max-age=600');     // 快取 10 分鐘,減少上游壓力

$cityCode = $_GET['city'] ?? '101280601'; // 預設深圳
$url = "https://www.weather.com.cn/data/sk/{$cityCode}.html";

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 5,
    CURLOPT_CONNECTTIMEOUT => 3,
    CURLOPT_USERAGENT      => 'Mozilla/5.0 (Weather Proxy)',
]);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode !== 200 || empty($data)) {
    http_response_code(502);
    echo json_encode(['error' => '上游服務不可用']);
    exit;
}

// 直接透傳上游 JSON(已為 UTF-8)
echo $data;

前端頁面 (index.html)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>即時天氣</title>
<style>
.weather-card { max-width: 400px; margin: 2rem auto; padding: 1.5rem; font-family: sans-serif; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.1); }
.weather-row { display: flex; justify-content: space-between; margin: .5rem 0; font-size: 1.1rem; }
.weather-label { color: #666; }
.weather-value { font-weight: 600; color: #2c3e50; }
.error { color: #e74c3c; text-align: center; padding: 2rem; }
</style>
</head>
<body>
<div class="weather-card" id="weather">
    <div class="weather-row"><span class="weather-label">城市</span><span class="weather-value" id="city">載入中…</span></div>
    <div class="weather-row"><span class="weather-label">溫度</span><span class="weather-value" id="temp">--</span></div>
    <div class="weather-row"><span class="weather-label">風向</span><span class="weather-value" id="wind">--</span></div>
    <div class="weather-row"><span class="weather-label">風力</span><span class="weather-value" id="windPower">--</span></div>
    <div class="weather-row"><span class="weather-label">濕度</span><span class="weather-value" id="humidity">--</span></div>
    <div class="weather-row"><span class="weather-label">更新時間</span><span class="weather-value" id="time">--</span></div>
</div>

<script>
// 原生 fetch,無需 jQuery
async function loadWeather() {
    try {
        const res = await fetch('weather.php?city=101280601');
        if (!res.ok) throw new Error('網路錯誤');
        const data = await res.json();
        if (data.error) throw new Error(data.error);

        const info = data.weatherinfo || data;
        document.getElementById('city').textContent = info.city ?? '未知';
        document.getElementById('temp').textContent = (info.temp ?? '--') + '°C';
        document.getElementById('wind').textContent = info.WD ?? '--';
        document.getElementById('windPower').textContent = info.WS ?? '--';
        document.getElementById('humidity').textContent = (info.SD ?? '--').replace('%', '') + '%';
        document.getElementById('time').textContent = info.time ?? '--';
    } catch (e) {
        document.getElementById('weather').innerHTML = '<div class="error">載入失敗:' + e.message + '</div>';
    }
}
loadWeather();
// 可選:每 10 分鐘自動更新
setInterval(loadWeather, 10 * 60 * 1000);
</script>
</body>
</html>

API 回傳欄位對照表

欄位含義範例
city城市名稱深圳
temp當前溫度(℃)28
WD風向東南風
WS風力等級3級
SD相對濕度78%
time發布時間14:30
cityid城市代碼101280601

常見城市代碼

  • 北京:101010100
  • 上海:101020100
  • 廣州:101280101
  • 深圳:101280601
  • 成都:101270101

完整列表可從 https://www.weather.com.cn/data/city3jdata/china.html 獲取。

生產環境優化建議

  1. 快取層:Redis 快取 5-10 分鐘,Key 格式 weather:{cityCode}
  2. 錯誤降級:上游失敗時回傳上次成功快取或靜態預設值
  3. HTTPS 代理:若網站為全站 HTTPS,務必使用 PHP 代理避免混合內容阻擋
  4. 多城市支援:前端提供下拉選單切換城市,傳遞 city 參數
  5. 監控告警:記錄上游回應時間、錯誤率,異常時發送告警
copyright © 萬盛學電腦網 all rights reserved