本文提供一套完整的 PHP 天氣預報抓取方案,資料來源為中央氣象局,涵蓋全台縣市鄉鎮。程式碼內建 XML 快取機制、編碼自動轉換、多層級地區代碼解析,輸出標準 JSON 格式,適合前端直接呼叫或後端二次處理。
data/ 目錄快取 XML,降低對外請求頻率<?php
/**
* 作者:freemouse
* 來源:www.cnphp.info
* 用法:直接存取本檔案顯示當地天氣,或加參數 ?q=江蘇省南京市
* 注意:需建立 data/ 目錄並設定可寫入權限
*/
$p = isset($_GET['q']) ? $_GET['q'] : '';
$k = 0;
$encoding = mb_detect_encoding($p);
if ($encoding !== 'UTF-8') {
$p = mb_convert_encoding($p, 'UTF-8', 'GBK');
}
// 縣市代碼對照表 (01~34)
$p_arr = array(
"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" => "台灣"
);
// 遞迴搜尋關鍵字對應的代碼
function find(&$item, $key, $data) {
global $k;
if (preg_match("/$item/u", $data)) {
$k = $key;
}
}
// 取得指定代碼的下層資料 (支援快取)
function get_data_arr($key) {
$cache_file = "./data/city{$key}.xml";
if (!file_exists($cache_file)) {
$c = file_get_contents("https://m.weather.com.cn/data5/city{$key}.xml");
file_put_contents($cache_file, $c);
} else {
$c = file_get_contents($cache_file);
}
$arr = explode(",", $c);
$ret = array();
foreach ($arr as $v) {
$data = explode("|", $v);
$ret[$data[0]] = $data[1];
}
return $ret;
}
// 1. 找出縣市代碼
array_walk($p_arr, 'find', $p);
// 2. 找出鄉鎮代碼
array_walk(get_data_arr($k), 'find', $p);
// 3. 找出村里/測站代碼
array_walk(get_data_arr($k), 'find', $p);
// 取得最終代碼並輸出天氣 JSON
$ccode = get_data_arr($k);
echo file_get_contents("https://m.weather.com.cn/data/{$ccode[$k]}.html");
?>
data/ 目錄並設定寫入權限:mkdir data && chmod 777 dataallow_url_fopen 或 cURL 擴展{code, message, data} 結構,方便前端處理此方案已實戰應用於 WordPress 天氣外掛,穩定可靠。只需部署單一 PHP 檔案即可快速接入全國天氣資料。