fcb1900
fcb1900

Reputation: 359

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

Upvotes: 1

Views: 4979

Answers (3)

Devsaiful
Devsaiful

Reputation: 157

Lets try it...

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

Upvotes: 2

Lex Lustor
Lex Lustor

Reputation: 1615

You used json_decode with parameter associative to true.

So $data is rather an array not an object.

Based on that sample (similar to your url), you should access your values with square bracket syntax :

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

Upvotes: 1

Tim Krins
Tim Krins

Reputation: 3819

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

Upvotes: 6

Related Questions