首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

串接中國天氣網 API 實現即時天氣顯示:PHP 後端 + jQuery 前端完整範例

     編輯:PHP 相關知識

中國天氣網提供公開的即時天氣介面(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 取得完整列表。
  • 後端代理可加入 Redis 快取(TTL 10-30 分鐘),降低上游壓力並提升回應速度。
  • 生產環境建議改用官方付費 API 或支援 HTTPS 的服務(如和風天氣、OpenWeatherMap)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved