Error "Message: Trying to get property of non-object" when trying to retrieve an array

ServerSideSkittles picture ServerSideSkittles · Apr 27, 2013 · Viewed 7.2k times · Source

I am trying to request some data using json and the wunderground API.

When I use this code it returns the error "Message: Trying to get property of non-object".

<?php

  $json_string = file_get_contents("http://api.wunderground.com/api/1e6a89f0a3aa092d/alerts/q/zmw:00000.1.16172.json");
  $parsed_json = json_decode($json_string);
  $wColor = $parsed_json->{'alerts'}->{'attribution'};
  $wName = $parsed_json->{'alerts'}->{'wtype_meteoalarm'};
  echo "Severe weather alert ${wColor} expected ${wName} - MORE INFO";

?>

The Data is there and can be viewed here...

http://api.wunderground.com/api/1e6a89f0a3aa092d/alerts/q/zmw:00000.1.16172.json

Yet when I use the almost identical example code snippet from the documentation

<?php
  $json_string = file_get_contents("http://api.wunderground.com/api/1e6a89f0a3aa092d/geolookup/conditions/q/IA/Cedar_Rapids.json");
  $parsed_json = json_decode($json_string);
  $location = $parsed_json->{'location'}->{'city'};
  $temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
  echo "Current temperature in ${location} is: ${temp_f}\n";
?> 

It works absolutely fine! How come I the first request fails to work?

Answer

bwoebi picture bwoebi · Apr 27, 2013

$parsed_json->alerts is here a numeric array containing objects:

The var_dump()'ed output of it:

object(stdClass)#1 (2) {
  ["response"]=> ...

  ["alerts"]=>
  array(1) {
    [0]=>
    object(stdClass)#4 (15) {
      ["type"]=>
      string(3) "WRN"
      ...
    }
  }
}

So use:

$wColor = $parsed_json->alerts[0]->attribution;
$wName = $parsed_json->alerts[0]->wtype_meteoalarm;