萬盛學電腦網

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

PHP 采集中國中央氣象台全國天氣預報數據完整實現

需求

獲取權威、覆蓋全國、免費的天氣預報數據,用於網站展示、小程序、App 推送。中國中央氣象台 (weather.com.cn) 提供開放接口,返回 JSON,支援省市區三級查詢。

接口分析

  1. 城市列表:https://m.weather.com.cn/data5/city{code}.xml,code 為省份代碼 (01-34),返回 城市代碼|城市名,... 格式。
  2. 天氣詳情:https://m.weather.com.cn/data/{cityCode}.html,返回 JSON:{weatherinfo: {city, temp, WD, WS, ...}}。
  3. 三級查找:省份 → 城市 → 區/縣,逐級獲取代碼。

完整採集類

<?php
class WeatherCollector {
    private const BASE_URL = 'https://m.weather.com.cn';
    private string $cacheDir;
    private array $provinceMap = [
        '01' => '北京', '02' => '上海', '03' => '天津', '04' => '重慶',
        '05' => '黑龍江', '06' => '吉林', '07' => '遼寧', '08' => '內蒙古',
        '09' => '河北', '10' => '山西', '11' => '陝西', '12' => '山東',
        '13' => '新疆', '14' => '西藏', '15' => '青海', '16' => '甘肅',
        '17' => '寧夏', '18' => '河南', '19' => '江蘇', '20' => '湖北',
        '21' => '浙江', '22' => '安徽', '23' => '福建', '24' => '江西',
        '25' => '湖南', '26' => '貴州', '27' => '四川', '28' => '廣東',
        '29' => '雲南', '30' => '廣西', '31' => '海南', '32' => '香港',
        '33' => '澳門', '34' => '台灣',
    ];

    public function __construct(string $cacheDir = './data') {
        $this->cacheDir = rtrim($cacheDir, '/');
        if (!is_dir($this->cacheDir)) mkdir($this->cacheDir, 0755, true);
    }

    /**
     * 根據中文地址獲取天氣 (如 "江蘇省南京市鼓樓區")
     */
    public function getWeatherByAddress(string $address): ?array {
        // 1. 標準化編碼
        $address = $this->normalizeEncoding($address);

        // 2. 三級匹配:省 -> 市 -> 區
        $provinceCode = $this->matchProvince($address);
        if (!$provinceCode) return null;

        $cityCode = $this->matchCity($provinceCode, $address);
        if (!$cityCode) return null;

        $districtCode = $this->matchDistrict($cityCode, $address);
        $finalCode = $districtCode ?? $cityCode;

        // 3. 獲取天氣 JSON
        return $this->fetchWeather($finalCode);
    }

    private function normalizeEncoding(string $str): string {
        $enc = mb_detect_encoding($str, ['UTF-8', 'GBK', 'GB2312'], true);
        if ($enc && $enc !== 'UTF-8') {
            return mb_convert_encoding($str, 'UTF-8', $enc);
        }
        return $str;
    }

    private function matchProvince(string $address): ?string {
        foreach ($this->provinceMap as $code => $name) {
            if (mb_strpos($address, $name) !== false) return $code;
        }
        return null;
    }

    private function matchCity(string $provinceCode, string $address): ?string {
        $cities = $this->fetchCityList($provinceCode);
        foreach ($cities as $code => $name) {
            if (mb_strpos($address, $name) !== false) return $code;
        }
        return null;
    }

    private function matchDistrict(string $cityCode, string $address): ?string {
        $districts = $this->fetchCityList($cityCode); // 同一接口,城市代碼下級為區縣
        foreach ($districts as $code => $name) {
            if (mb_strpos($address, $name) !== false) return $code;
        }
        return null;
    }

    private function fetchCityList(string $code): array {
        $cacheFile = "{$this->cacheDir}/city{$code}.xml";
        if (file_exists($cacheFile) && time() - filemtime($cacheFile) < 3600) {
            $content = file_get_contents($cacheFile);
        } else {
            $content = @file_get_contents(self::BASE_URL . "/data5/city{$code}.xml");
            if ($content) @file_put_contents($cacheFile, $content);
        }
        if (!$content) return [];
        
        $result = [];
        foreach (explode(',', $content) as $pair) {
            [$c, $n] = explode('|', $pair) + ['', ''];
            if ($c && $n) $result[$c] = $n;
        }
        return $result;
    }

    private function fetchWeather(string $code): ?array {
        $url = self::BASE_URL . "/data/{$code}.html";
        $json = @file_get_contents($url);
        if (!$json) return null;
        $data = json_decode($json, true);
        return $data['weatherinfo'] ?? null;
    }
}

// ===== 使用 =====
$collector = new WeatherCollector();
$weather = $collector->getWeatherByAddress('江蘇省南京市鼓樓區');
if ($weather) {
    echo "城市: {$weather['city']}\n";
    echo "溫度: {$weather['temp']}°C\n";
    echo "風向: {$weather['WD']} {$weather['WS']}\n";
    echo "濕度: {$weather['SD']}\n";
    echo "發布時間: {$weather['time']}\n";
} else {
    echo "未找到該地區天氣\n";
}

緩存策略

  • 城市列表 XML:緩存 1 小時 (變動極少)。
  • 天氣 JSON:緩存 10-30 分鐘 (按實際更新頻率)。
  • 生產環境建議用 Redis 替代文件緩存,支援集群。

法律與道德合規

  1. 中央氣象台數據屬公共氣象服務,非商業用途一般允許,商業用途需申請授權。
  2. 請求頻率控制:單 IP 每分鐘 < 60 次,避免被封禁。
  3. 註明數據來源:數據來源:中國天氣網 / 中央氣象台。

擴展:支援坐標反查

若有經緯度,可先調用高德/騰訊地圖 API 逆地理編碼獲取標準地址,再走本流程。

總結

基於中央氣象台開放接口的三級代碼查找 + 本地緩存,可穩定獲取全國天氣預報。核心難點在於中文地址匹配的容錯(簡稱、別名、行政區劃變更),建議引入標準行政區劃庫 (如 china-area-data) 做精確映射。

copyright © 萬盛學電腦網 all rights reserved