首页 > 解决方案 > 在 PHP 中使用 OpenWeatherMap 预报 API

问题描述

我正在尝试从 openweathermap 显示一个城市的预测。但我的 foreach 什么也没显示。怎么了?

<?php
  $url = "http://api.openweathermap.org/data/2.5/forecast?zip=85080,de&lang=de&APPID=MYKEY";

  $contents = file_get_contents($url);
  $clima = json_decode($contents, true);

  foreach($clima as $data) {
    echo $data->list->main->temp_min;
  }
?>

标签: phpjsonapiopenweathermap

解决方案


a 的结果json_decode(string, true)是一个关联数组。

<?php

  $url = "http://api.openweathermap.org/data/2.5/forecast?zip=85080,de&lang=de&APPID=MYKEY";

  $contents = file_get_contents($url);
  $clima = json_decode($contents, true);

  foreach($clima['list'] as $data) {
    echo $data['main']['temp_min'];
  }

?>

如果要使用对象语法,请不要将关联设置为true.

$clima = json_decode($contents);

foreach($clima->list as $data) {
  echo $data->main->temp_min;
}

推荐阅读