PHP JSON extracting specific forecast data

  • 1
  • Question
  • Updated 4 years ago
I found some (most) of the following code on wunderground and it works. I can't figure out how to directly pull out specific information. Here's the code that will run as is:

$value)
{
if (is_object($value))
{
iterate("${name}->${key}", $value);
}
else if (is_array($value))
{
$n = count($value);
for ($i = 0; $i < $n; ++$i)
{
if (is_object($value[$i]))
{
iterate("${name}->${key}[$i]", $value[$i]);
}
else
{
print "${name}->${key}[$i] = '$value'\n";
echo "
";
}
}
}
else
{
print "${name}->${key} = '$value'\n";
echo "
";
print "${name}->${key} = '$value'\n";
print "$name->$key\n";
print_r ($value);
echo "

";
}
}

}

$api = 'http://api.wunderground.com/api';
$key = 'a66c7dca62f80c59'; //
$features = 'geolookup/forecast10day'; // your desired features here
$query = 'q/MA/KBOS'; // your query here
$data = json_decode(file_get_contents("$api/$key/$features/q/$query.json"));

iterate('data', $data);

Now's here the code that I added but is not working:

$test = $data->{'forecast'}->{'txt_forecast'}->{'forecastday[4]'}->{'fcttext'};
print "$test";

?>

I've decoded the json query into $data but how do I get at a specific piece of information?
Photo of rslotpole1

rslotpole1

  • 2 Posts
  • 0 Reply Likes

Posted 4 years ago

  • 1
Photo of rslotpole1

rslotpole1

  • 2 Posts
  • 0 Reply Likes
the trick here is to first use the true option in decode
$data = json_decode(file_get_contents("$api/$key/$features/q/$query.json"),true);

and then to use:
print_r (array_keys($data));

but then you need to do that for each level you want to go down
Photo of afelicioni

afelicioni

  • 227 Posts
  • 43 Reply Likes
seen from outside, is unclear what you expect to get, and if you prefer to code with "object oriented" or "procedural" syntax.

anyway trying to guess... you were at last just seeking for a "hard path" to get textual forecast in procedural style for that specific piece of information.
so when the JSON is decoded as associative arrays, the following code works

$test = $data['forecast']['txt_forecast']['forecastday'][4]['fcttext'];