萬盛學電腦網

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

PHP + AJAX 即時天氣預報模組:串接中國天氣網 API

API 端點 (中國天氣網)

介面URL 範例說明
即時天氣https://www.weather.com.cn/data/sk/101010100.html溫度、濕度、風向、風力、更新時間
城市資訊https://www.weather.com.cn/data/cityinfo/101010100.html城市代碼、名稱、父級代碼
多日預報https://m.weather.com.cn/data/101010100.html未來 7 天預報

注意: 非官方公開文檔介面,隨時可能變更或限流。生產環境建議申請商業授權或使用彩雲天氣、和風天氣等正規 API。

前端頁面 (index.php)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>天氣預報</title>
    <style>body{font-family:sans-serif;padding:2rem;} select{padding:.5rem;} #weather{margin-top:1rem;padding:1rem;background:#f5f5f5;}</style>
</head>
<body>
    <select id="cityId" onchange="loadWeather()">
        <option value="">-- 請選擇城市 --</option>
        <option value="101010100">北京</option>
        <option value="101020100">上海</option>
        <option value="101030100">天津</option>
        <option value="101040100">重慶</option>
        <option value="101280101">廣州</option>
    </select>
    <div id="weather">請選擇城市</div>

    <script>
    function loadWeather() {
        const cityId = document.getElementById('cityId').value;
        const box = document.getElementById('weather');
        if (!cityId) { box.textContent = '請選擇城市'; return; }
        box.textContent = '載入中...';

        fetch('weather.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'cityid=' + encodeURIComponent(cityId)
        })
        .then(r => r.text())
        .then(html => { box.innerHTML = html; })
        .catch(err => { box.textContent = '載入失敗: ' + err; });
    }
    </script>
</body>
</html>

後端代理 (weather.php)

<?php
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');

$cityId = $_POST['cityid'] ?? '101010100';
// 簡單驗證:純數字 9 碼
if (!preg_match('/^\d{9}$/', $cityId)) {
    $cityId = '101010100';
}

$url = "https://www.weather.com.cn/data/sk/{$cityId}.html";
$json = @file_get_contents($url);

if ($json === false) {
    echo '無法取得天氣資料';
    exit;
}

$data = json_decode($json, true);
if (!isset($data['weatherinfo'])) {
    echo '資料格式異常';
    exit;
}

$w = $data['weatherinfo'];
$html = <<{$w['city']} ({$w['time']})
溫度: {$w['temp']}°C
濕度: {$w['SD']}
風向: {$w['WD']} {$w['WS']} HTML; echo $html; ?>

進階:快取與容錯

<?php
// 使用 Redis 快取 10 分鐘
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cacheKey = "weather:sk:{$cityId}";

if (($cached = $redis->get($cacheKey)) !== false) {
    echo $cached;
    exit;
}

// 取得並快取
$json = @file_get_contents($url);
if ($json) {
    $redis->setex($cacheKey, 600, $json); // 10 分鐘
    // ... 後續解析輸出
}
?>

安全性建議

  • 後端代理隱藏上游 API 細節,避免前端直接呼叫跨域/被封鎖。
  • 驗證 cityid 格式,防止 SSRF (Server-Side Request Forgery)。
  • 設定合理的 file_get_contents 超時:stream_context_create(['http'=>['timeout'=>5]])。
copyright © 萬盛學電腦網 all rights reserved