Search code examples
phpjsonopenweathermap

Using OpenWeatherMap forecast API in PHP


I am trying to show the forecast for a city from openweathermap. But my foreach show nothing. Whats wrong?

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

Solution

  • The result from a json_decode(string, true) is an associative array.

    <?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'];
      }
    
    ?>
    

    If you want to use object syntax, don't set associative to true.

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