本文示範如何使用 PHP 從百度搜尋結果中解析天氣資訊,實作簡易的城市天氣查詢功能。
https://www.baidu.com/s?wd={城市}天氣file() 讀取搜尋結果頁面<form method="post">
<input name="a" type="text" id="a" />
<input type="submit" name="Submit" value="查" />
</form>
<?php
$city = $_REQUEST["a"];
if ($city == "") {
$city = "菏澤";
}
$url = 'https://www.baidu.com/s?wd=' . urlencode($city . '天氣');
$lines_array = file($url);
$lines_string = implode('', $lines_array);
// 使用 preg_match 替代已棄用的 eregi
if (preg_match('/今天((.*)今日氣象指數/s', $lines_string, $body)) {
$weather = strip_tags($body[0]);
$weather = str_replace(" 今日氣象指數", "", $weather);
$weather = str_replace(" ", "", $weather);
echo $city . $weather;
}
?>
urlencode() 處理中文城市名,避免 URL 錯誤eregi() 已在 PHP 5.3.0 棄用,改用 preg_match() 搭配 /i 修飾符preg_match 回傳值判斷,避免解析失敗時出現 Notice由於搜尋引擎頁面結構頻繁變動,建議改用官方天氣 API:
<?php
$apiKey = "YOUR_API_KEY";
$city = "北京";
$url = "https://devapi.qweather.com/v7/weather/now?location={$city}&key={$apiKey}";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_TIMEOUT => 10
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if ($data['code'] === '200') {
echo "{$city} 現在溫度:{$data['now']['temp']}°C,{$data['now']['text']}";
}
?>
透過官方 API 可獲得結構化、穩定、可靠的天氣資料,是生產環境的最佳選擇。