百度地圖開放平台提供免費天氣查詢 API,回傳結構化 JSON,含當前天氣、未來 3 天預報、生活指數等,穩定性遠優於網頁爬蟲。本文示範從 AK 申請到程式碼整合的完整流程。
GET https://api.map.baidu.com/telematics/v3/weather
參數:
location (必填) : 城市名稱或經緯度,中文需 URL 編碼
output (選填) : json / xml (預設 xml)
ak (必填) : 您的 AK
callback (選填) : JSONP 回調函數名
<?php
function getBaiduWeather(string $city, string $ak): ?array
{
$url = 'https://api.map.baidu.com/telematics/v3/weather?' . http_build_query([
'location' => $city,
'output' => 'json',
'ak' => $ak,
]);
$json = @file_get_contents($url);
if ($json === false) {
error_log("百度天氣 API 請求失敗: $city");
return null;
}
$data = json_decode($json, true);
if (($data['error'] ?? 1) !== 0) {
error_log("百度天氣 API 回傳錯誤: " . ($data['status'] ?? 'unknown'));
return null;
}
return $data['results'][0] ?? null;
}
// === 使用範例 ===
$ak = '您的AK'; // 替換為真實 AK
$city = '嘉興';
$weather = getBaiduWeather($city, $ak);
if ($weather) {
echo "城市: {$weather['currentCity']}\n";
foreach ($weather['weather_data'] as $day) {
echo "{$day['date']} | {$day['weather']} | {$day['temperature']} | {$day['wind']}\n";
}
} else {
echo "獲取天氣失敗,請檢查 AK 或網路。\n";
}
[
"error" => 0,
"status" => "success",
"date" => "2024-05-20",
"results" => [
{
"currentCity": "嘉興",
"pm25": "45",
"weather_data": [
{
"date": "今天 (週一)",
"dayPictureUrl": "https://api.map.baidu.com/images/weather/day/qing.png",
"nightPictureUrl": "https://api.map.baidu.com/images/weather/night/qing.png",
"weather": "晴",
"wind": "東南風 3-4 級",
"temperature": "28~18℃"
},
{ ... 明天 ... },
{ ... 後天 ... },
{ ... 大後天 ... }
],
"index": [
{ "title": "穿衣", "zs": "較舒適", "tipt": "建議穿長袖..." },
{ "title": "洗車", "zs": "較適宜", "tipt": "未來一天無雨..." },
{ "title": "感冒", "zs": "少發", "tipt": "氣溫變化不大..." },
{ "title": "運動", "zs": "較適宜", "tipt": "室外運動請注意..." },
{ "title": "紫外線", "zs": "中等", "tipt": "外出請塗抹防曬..." }
]
}
]
]
location=31.2304,121.4737 (上海市中心),適用於無城市名稱的定位場景。weather:{city} TTL 7200 秒,減少 API 配額消耗。https://api.map.baidu.com/...,確保傳輸加密。| error | status | 原因 | 解決 |
|---|---|---|---|
| 1 | AK 驗證失敗 | AK 無效/未啟用服務/IP 不在白名單 | 檢查控制台 AK 狀態與白名單 |
| 2 | 無權限 | 未勾選「天氣查詢」服務 | 控制台啟用對應服務 |
| 3 | 配額超限 | 日請求超過免費額度 (通常 1萬/日) | 申請提額或增加快取 |
| 4 | 參數錯誤 | location 為空或格式錯誤 | 確保城市名 URL 編碼正確 |
採用官方 API 不僅合規穩定,更能獲得 PM2.5、生活指數等豐富維度資料,是 PHP 專案接入天氣功能的首選方案。