| 介面 | URL 範例 | 說明 |
|---|---|---|
| 即時天氣 | https://www.weather.com.cn/data/sk/101010100.html | 溫度、濕度、風向、風力、更新時間 |
| 城市資訊 | https://www.weather.com.cn/data/cityinfo/101010100.html | 城市代碼、名稱、父級代碼 |
| 多日預報 | https://m.weather.com.cn/data/101010100.html | 未來 7 天預報 |
注意: 非官方公開文檔介面,隨時可能變更或限流。生產環境建議申請商業授權或使用彩雲天氣、和風天氣等正規 API。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>天氣預報</title>
<style>body{font-family:sans-serif;padding:2rem;} select{padding:.5rem;} #weather{margin-top:1rem;padding:1rem;background:#f5f5f5;}</style>
</head>
<body>
<select id="cityId" onchange="loadWeather()">
<option value="">-- 請選擇城市 --</option>
<option value="101010100">北京</option>
<option value="101020100">上海</option>
<option value="101030100">天津</option>
<option value="101040100">重慶</option>
<option value="101280101">廣州</option>
</select>
<div id="weather">請選擇城市</div>
<script>
function loadWeather() {
const cityId = document.getElementById('cityId').value;
const box = document.getElementById('weather');
if (!cityId) { box.textContent = '請選擇城市'; return; }
box.textContent = '載入中...';
fetch('weather.php', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: 'cityid=' + encodeURIComponent(cityId)
})
.then(r => r.text())
.then(html => { box.innerHTML = html; })
.catch(err => { box.textContent = '載入失敗: ' + err; });
}
</script>
</body>
</html>
<?php
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
$cityId = $_POST['cityid'] ?? '101010100';
// 簡單驗證:純數字 9 碼
if (!preg_match('/^\d{9}$/', $cityId)) {
$cityId = '101010100';
}
$url = "https://www.weather.com.cn/data/sk/{$cityId}.html";
$json = @file_get_contents($url);
if ($json === false) {
echo '無法取得天氣資料';
exit;
}
$data = json_decode($json, true);
if (!isset($data['weatherinfo'])) {
echo '資料格式異常';
exit;
}
$w = $data['weatherinfo'];
$html = <<{$w['city']} ({$w['time']})
溫度: {$w['temp']}°C
濕度: {$w['SD']}
風向: {$w['WD']} {$w['WS']}
HTML;
echo $html;
?>
<?php
// 使用 Redis 快取 10 分鐘
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$cacheKey = "weather:sk:{$cityId}";
if (($cached = $redis->get($cacheKey)) !== false) {
echo $cached;
exit;
}
// 取得並快取
$json = @file_get_contents($url);
if ($json) {
$redis->setex($cacheKey, 600, $json); // 10 分鐘
// ... 後續解析輸出
}
?>
cityid 格式,防止 SSRF (Server-Side Request Forgery)。file_get_contents 超時:stream_context_create(['http'=>['timeout'=>5]])。