Search code examples
phpjsonweather-apiopenweathermap

JSON Weather Feed in PHP


I am trying to display this weather information by pulling it from a JSON feed in PHP. I can't figure out why it is not printing. Here is the code:

$url="http://api.openweathermap.org/data/2.5/forecast?q=Albany,usl&APPID=5099c5feb579c7a17b030de0d009282f&units=metric";
$json=file_get_contents($url);
$data=json_decode($json);



echo '<h1>', $data->name, ' (', $data->sys->country, ')</h1>';

// the general information about the weather
echo '<h2>Temperature:</h2>';
echo '<p><strong>Current:</strong> ', $data->main->temp, '&deg; C</p>';
echo '<p><strong>Min:</strong> ', $data->main->temp_min, '&deg; C</p>';
echo '<p><strong>Max:</strong> ', $data->main->temp_max, '&deg; C</p>';

?>

My output is something like:

()

Temperature:

Current: ° C

Min: ° C

Max: ° C


Solution

  • There is a problem with the way you parse the output from the API. Check bellow -

        $url="http://api.openweathermap.org/data/2.5/forecast?q=Albany,usl&APPID=5099c5feb579c7a17b030de0d009282f&units=metric";
        $json=file_get_contents($url);
        $data=json_decode($json);
    
        echo '<h1>', $data->city->name, ' (', $data->city->country, ')</h1>';
    
        // the general information about the weather
        echo '<h2>Temperature:</h2>';
        echo '<p><strong>Current:</strong> ', $data->list[0]->main->temp, '&deg; C</p>';
        echo '<p><strong>Min:</strong> ', $data->list[0]->main->temp_min, '&deg; C</p>';
        echo '<p><strong>Max:</strong> ', $data->list[0]->main->temp_max, '&deg; C</p>';