
本文详解如何通过 OpenWeatherMap 的 forecast/daily API 获取未来3天的每日最高与最低温度,并避免使用错误的 3 小时粒度接口,附完整 PHP 示例与关键注意事项。
本文详解如何通过 openweathermap 的 `forecast/daily` api 获取未来3天的每日最高与最低温度,并避免使用错误的 3 小时粒度接口,附完整 php 示例与关键注意事项。
OpenWeatherMap 提供两类主流天气预报接口:/forecast(每3小时一次,共5天40条记录)和 /forecast/daily(按天聚合,含日均温、日极值等)。题中问题的根本原因在于误用了 /forecast 接口——该接口中 temp_max 和 temp_min 并非当日极值,而是未来3小时内预测的最高/最低温度(即滚动窗口值),因此无法直接用于“每日最高温/最低温”展示。
要实现如 Thursday 15.09: Max: 25°C / Min: 20°C 这类标准日预报,必须切换至已正式支持(且文档明确标注为“Deprecated but still available”的过渡期稳定接口)的 /data/2.5/forecast/daily 端点。该接口返回结构清晰的每日聚合数据,每个 list 元素代表一天,其 temp.day、temp.min、temp.max 字段即为当日白天均温、全天最低温、全天最高温(单位:°C,当 units=metric 时无需手动转换)。
以下是推荐的完整实现方案:
<?php
$api_key = 'YOUR_API_KEY';
$maxDays = 3;
$query = http_build_query([
'q' => 'Berlin,DE',
'cnt' => $maxDays,
'units' => 'metric', // 自动返回摄氏度,无需 -273.15 转换
'lang' => 'de',
'appid' => $api_key
]);
$url = 'https://api.openweathermap.org/data/2.5/forecast/daily?' . $query;
$json = file_get_contents($url);
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE || !isset($data['list'])) {
die('API 请求失败或响应格式异常');
}
echo '<table border="1" class="forecast-table"><tbody>';
foreach ($data['list'] as $day) {
$date = date('l d.m', $day['dt']); // e.g. "Thursday 15.09"
$max_temp = round($day['temp']['max'], 1) . '°C';
$min_temp = round($day['temp']['min'], 1) . '°C';
echo "<tr>
<td><strong>{$date}:</strong></td>
<td>Max: {$max_temp}</td>
<td>/Min: {$min_temp}</td>
</tr>";
}
echo '</tbody></table>';
?>✅ 关键要点说明:
- ✅ 使用
forecast/daily而非forecast,确保数据按“自然日”聚合; - ✅ 设置
units=metric后,所有温度字段(temp.max/temp.min)直接为摄氏度,无需再减 273.15; - ✅
cnt=3精确控制返回天数(最多16天),避免冗余解析; - ⚠️ 注意:
forecast/daily接口虽仍可用,但 OpenWeatherMap 已在文档中建议迁移到/weather+geocoding+onecall组合方案(适用于长期项目);若需更长周期或分钟级降水,应评估onecall(需经纬度); - ⚠️ 城市参数建议精简为
'Berlin,DE',重复国家码(如Berlin,DE,DE)可能引发解析异常; - ? 增强健壮性:务必检查
json_decode结果及list键是否存在,避免空响应导致 PHP 警告。
通过以上调整,即可稳定输出符合业务需求的、语义准确的3天日温度预报,代码简洁、逻辑清晰、维护成本低。

















