中國天氣網公開 API:https://www.weather.com.cn/data/cityinfo/{城市ID}.html
返回 JSON:{"weatherinfo":{"city":"武漢","cityid":"101200101","temp1":"28℃","temp2":"36℃","weather":"晴轉多雲","img1":"n0.gif","img2":"d1.gif","ptime":"18:00"}}
<?php
// citycode.php
$citycode = [
'北京' => '101010100', '上海' => '101020100', '廣州' => '101280101',
'深圳' => '101280601', '武漢' => '101200101', '成都' => '101270101',
// ... 更多城市
];
?>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
$(function(){
$("#submit").click(function(){
var city = $("#city").val();
$.post("getweather.php", {city: city}, function(data){
if (data.weatherinfo && data.weatherinfo.city) {
var w = data.weatherinfo;
alert(w.city + ": " + w.weather + ", " + w.temp2 + " - " + w.temp1);
} else {
alert("未找到該城市");
}
}, "json");
});
});
</script>
<form method="post">
請輸入城市:<input type="text" name="city" id="city" value="武漢">
<input type="button" id="submit" value="查看天氣">
</form>
<?php
include "citycode.php";
$city = $_POST['city'] ?? '';
$code = $citycode[$city] ?? '';
if (empty($code)) {
echo json_encode(['error' => '城市不在支持範圍內']);
} else {
// 直接透傳 API 返回
echo file_get_contents("https://www.weather.com.cn/data/cityinfo/{$code}.html");
}
?>
通過 PHP 後端代理調用中國天氣網 API,配合前端 AJAX 免刷新體驗,快速實現天氣查詢功能。核心在於城市 ID 映射、跨域代理、緩存策略與錯誤容錯。