Question

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?

Was it helpful?

Solution 2

The problem was in the way you were retrieving the fields. Use:

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

OTHER TIPS

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

Try this

$alert = current($parsed_json->{'alerts'});
$wColor = $alert->{'attribution'};
$wName = $alert->{'wtype_meteoalarm'};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top