快速獲取指定城市的天氣資料,無需申請 API 金鑰,直接解析百度搜尋結果頁面。
<?php
// 目標城市:北京(URL 編碼後為 %B1%B1%BE%A9%CC%EC%C6%F8)
$url = "https://www.baidu.com/s?wd=%B1%B1%BE%A9%CC%EC%C6%F8";
$content = file_get_contents($url);
// 以正則提取 id="weat" 區塊內的表格內容
preg_match_all('/<div id="weat">(.+?)<\/table>/si', $content, $temp);
// 再提取 td 標籤內的文字
preg_match_all('/<td>(.+?)<\/td>/si', $temp[1][0], $temp1);
var_dump($temp1[1][0]);
?>
string(243) "北京天氣
今天:溫度22℃ - 24℃。白天:多雲, 大陣雨,夜間:多雲。東風2級轉1-2級
明天:溫度23℃ - 28℃。白天:多雲,夜間:多雲。東南風2級"
urlencode(),百度頁面編碼通常為 GBK,若輸出亂碼請用 iconv() 轉碼。file_get_contents 回傳值,捕獲網路異常。function getBaiduWeather($city) {
$encodedCity = urlencode($city);
$url = "https://www.baidu.com/s?wd={$encodedCity}%E5%A4%A9%E6%B0%A3";
$html = @file_get_contents($url);
if (!$html) return false;
if (preg_match('/<div id="weat">(.+?)<\/table>/si', $html, $m)
&& preg_match_all('/<td>(.+?)<\/td>/si', $m[1], $t)) {
return trim($t[1][0]);
}
return false;
}
// 使用範例
echo getBaiduWeather('上海');