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

PHP调用OpenWeatherMap Forecast API获取天气类型失败求助

问题分析与解决

你的代码里温度数据能正常获取,说明API请求和$data->list[0]->main的访问逻辑没问题,但天气类型获取失败的核心原因是:OpenWeatherMap的forecast接口返回的weather字段是一个数组,并非单个对象,直接用->weather->main访问会触发错误——数组无法通过对象属性的调用方式读取内容。

修正后的核心代码

将获取天气类型的那行代码修改为:

echo '<p><strong>actualy Weather:</strong> ', $data->list[0]->weather[0]->main, '</p>';

额外健壮性优化建议

为避免API返回数据异常(比如无天气信息)导致页面报错,建议增加存在性检查:

// 先验证weather数组是否存在且有效
if (!empty($data->list[0]->weather) && isset($data->list[0]->weather[0]->main)) {
    echo '<p><strong>actualy Weather:</strong> ', $data->list[0]->weather[0]->main, '</p>';
} else {
    echo '<p><strong>actualy Weather:</strong> 无法获取天气状况信息</p>';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:45:56