在PHP中使用OpenWeatherMap预测API

时间:2018-08-24 13:29:46

标签: php json api openweathermap

我正试图从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;
  }
?>

3 个答案:

答案 0 :(得分:1)

让我们尝试一下...

<?php
    $city    = 'Dhaka';
    $country = 'BD';
    $url     = 'http://api.openweathermap.org/data/2.5/forecast/daily?q=' . $city . ',' . $country . '&units=metric&cnt=7&lang=en&appid=c0c4a4b4047b97ebc5948ac9c48c0559';
    $json    = file_get_contents( $url );
    $data    = json_decode( $json, true );
    $data['city']['name'];
    // var_dump($data );
    
    foreach ( $data['list'] as $day => $value ) {
        echo 'Max temperature for day ' . $day
        . ' will be ' . $value['temp']['max'] . '<br />';
        echo '<img src="http://openweathermap.org/img/w/' . $value['weather'][0]['icon'] . '.png"
                    class="weather-icon" />';
    
    }

答案 1 :(得分:0)

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;
}

答案 2 :(得分:0)

您将json_decode的参数 associative 设置为true。

所以 $ data 而是一个数组,而不是一个对象。

基于该sample(类似于您的网址),您应该使用square bracket syntax访问值:

$data['main']['temp_min'];