為網站添加天氣預報功能可提升用戶黏性。因無法直接獲取氣象衛星數據,常見做法是編寫爬蟲抓取公開天氣網站的 HTML 頁面,解析所需資訊。本文以中國天氣網為例,示範簡單的 PHP 采集程式。
file_get_contents 或 cURL)$url = 'https://www.weather.com.cn/weather/101050101.shtml'; // 哈爾濱
$html = file_get_contents($url);
if ($html === false) {
die('無法獲取遠端頁面');
}
觀察頁面原始碼,未來 7 天預報位於 <!--day 1--> 至 <!--day 7--> 註釋之間:
$pattern = '/<!--day 1-->(.*)<!--day 7-->/s';
if (!preg_match($pattern, $html, $matches)) {
die('頁面結構異常,無法定位預報區塊');
}
$forecastBlock = $matches[1];
注意:s修飾符讓.匹配換行符;實際專案建議使用 DOMDocument + XPath 更穩健。
$forecastBlock = str_replace(
'<img src="',
'<img src="https://www.weather.com.cn',
$forecastBlock
);
$url = 'https://www.weather.com.cn/weather/101050101.shtml';
$html = file_get_contents($url);
$startDay = 1;
$endDay = 3; // 可調整抓取天數
if ($endDay > 7) {
die('超出預報範圍');
}
$pattern = "/<!--day $startDay-->(.*)<!--day $endDay-->/s";
preg_match($pattern, $html, $matches);
$forecast = str_replace('<img src="', '<img src="https://www.weather.com.cn', $matches[1]);
echo "未來 " . ($endDay - $startDay + 1) . " 天天氣預報(" . date('Y-m-d') . " 發布)";
echo $forecast;
DOMDocument + DOMXPath 比正則更穩定、可維護robots.txt、控制抓取頻率、確認資料授權條款相同技術棧可應用於:股票即時行情、新聞 RSS 聚合、電商比價、公開 API 無官方 SDK 時的替代方案。
簡單的 PHP 爬蟲幾行代碼即可實現,但生產環境需考慮穩定性、效能、合法性與維護性。建議優先尋找官方 API,無 API 時再考慮爬蟲,並做好監控與降級預案。