中國天氣網提供公開的即時天氣介面(https://www.weather.com.cn/data/sk/城市代碼.html),回傳 JSON 格式資料。本文示範 PHP 代理請求避免跨域,配合 jQuery AJAX 即時渲染。
<?php
// weather.php
header('Content-Type: application/json; charset=utf-8');
// 城市代碼對照表建議存資料庫/快取,此處示範北京(101010100)
$cityCode = $_GET['city'] ?? '101010100';
$url = "https://www.weather.com.cn/data/sk/{$cityCode}.html";
$ctx = stream_context_create([
'http' => ['timeout' => 5, 'header' => 'User-Agent: PHP Weather Proxy']
]);
$json = @file_get_contents($url, false, $ctx);
if ($json === false) {
http_response_code(502);
echo json_encode(['error' => 'Upstream unavailable']);
exit;
}
// 直接透傳(已為 UTF-8 JSON)
echo $json;
?>
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>即時天氣</title>
<style>
.weather-card { max-width: 400px; margin: 2rem auto; padding: 1.5rem; border: 1px solid #ddd; border-radius: 8px; font-family: sans-serif; }
.weather-card .label { color: #666; font-size: .9rem; }
.weather-card .value { font-size: 1.5rem; font-weight: bold; color: #333; }
</style>
</head><body>
<div class="weather-card">
<div><span class="label">城市:</span><span class="value" id="city">--</span></div>
<div><span class="label">氣溫:</span><span class="value" id="temp">--</span>°C</div>
<div><span class="label">風向:</span><span class="value" id="wind">--</span></div>
<div><span class="label">風力:</span><span class="value" id="windPower">--</span></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
$(function() {
$.ajax({
url: 'weather.php',
data: { city: '101280601' }, // 深圳
dataType: 'json',
success: function(res) {
if (res.error) return;
var info = res.weatherinfo;
$('#city').text(info.city);
$('#temp').text(info.temp);
$('#wind').text(info.WD);
$('#windPower').text(info.WS);
},
error: function() { console.warn('Weather load failed'); }
});
});
</script>
</body></html>
https://www.weather.com.cn/data/city3jdata.jsp 取得完整列表。