You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Wunderground API JSON解析异常:页面天气数据不更新求助

解决Wunderground API数据不更新的问题

你的核心问题是PHP的file_get_contents默认启用HTTP缓存机制,导致服务器重复返回缓存的旧数据;而直接访问API URL时绕过了本地缓存,因此能看到最新数据。以下是几种可行的解决办法:

方法1:禁用HTTP缓存请求头

通过自定义HTTP上下文,强制请求不使用缓存:

// 创建禁用缓存的请求上下文
$context = stream_context_create([
    'http' => [
        'header' => "Cache-Control: no-cache, no-store, must-revalidate\r\n" .
                    "Pragma: no-cache\r\n" .
                    "Expires: Thu, 01 Jan 1970 00:00:00 GMT\r\n"
    ]
]);

// 携带上下文发起请求
$json = file_get_contents('https://api.weather.com/v3/wx/forecast/daily/5day?geocode=51.42,17.26&format=json&units=m&language=pl-PL&apiKey=MY API KEY', false, $context);

方法2:添加随机参数绕过缓存

在API URL末尾添加时间戳,让每次请求的URL唯一,避免缓存命中:

// 追加时间戳参数,确保URL每次不同
$timestamp = time();
$url = "https://api.weather.com/v3/wx/forecast/daily/5day?geocode=51.42,17.26&format=json&units=m&language=pl-PL&apiKey=MY API KEY&t=$timestamp";
$json = file_get_contents($url);

方法3:检查服务器端缓存规则

如果网站使用Apache或Nginx,检查是否配置了针对API请求的缓存策略(比如mod_cache或Nginx的proxy_cache),确保这类动态请求不被服务器缓存。

额外代码优化建议

你当前直接拼接HTML的写法可以改用PHP heredoc语法,提升代码可读性:

echo <<<HTML
<table style='width: 100%;'>
    <tr>
        <td style='padding: 8px;text-align: center;width: 25%'><span style='font-size:18px; color:#c9c9c9'>{$day[1]}</span></td>
        <td style='padding: 8px;text-align: center;width: 25%'><span style='font-size:18px; color:#c9c9c9'>{$day[2]}</span></td>
        <td style='padding: 8px;text-align: center;width: 25%'><span style='font-size:18px; color:#c9c9c9'>{$day[3]}</span></td>
        <td style='padding: 8px;text-align: center;width: 25%'><span style='font-size:18px; color:#c9c9c9'>{$day[4]}</span></td>
    </tr>
    <!-- 其余表格行按此格式调整 -->
</table>
HTML;

内容的提问来源于stack exchange,提问作者Shamy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 18:47:15