I was wondering if I could please get some help with the following mistake that I am making...
I am trying to access data in a weather api and I can't seem to echo out the information that I need.
<?php
// fetch Aeris API output as a string and decode into an object
$response = file_get_contents("https://api.aerisapi.com/observations/closest?p=:auto&format=json&radius=50mi&filter=allstations&limit=5&fields=id,ob.tempF,ob.dewpointF,ob.humidity,ob.windSpeedMPH,ob.windDir,ob.weather,ob.heatindexF,ob.feelslikeF&client_id=fRqZ7kEn97lvuYQlIFZ8y&client_secret=GKl5UydVJoSP7UDxmXWx5J8pegsFybclACCyVksr");
$json = json_decode($response);
foreach ($json->response as $weather);
echo '<pre>'; var_dump($weather);
echo 'weather'->[ob];
?>
I get the following error:
( ! ) Parse error: syntax error, unexpected '[', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in C:\wamp64\www\aeris\aerisobs.php on line 10
I'm not sure what the error is?
If we just look at what $weather prints out as, it's the following:
C:\wamp64\www\aeris\aerisobs.php:9:
object(stdClass)[10]
public 'id' => string 'MID_F5795' (length=9)
public 'ob' =>
object(stdClass)[11]
public 'tempF' => int 68
public 'dewpointF' => int 64
public 'humidity' => int 88
public 'windSpeedMPH' => int 1
public 'windDir' => string 'NE' (length=2)
public 'weather' => string 'Cloudy with Mist and Fog' (length=24)
public 'heatindexF' => int 68
public 'feelslikeF' => int 68
If anyone would be so kind as to educate me on my error and how to access ob and then, for example, tempF and print out 68 so that I can get that to appear on a web page?
Thank you for any assistance that you may offer!
Justin
Not tested but this should work for you to get inner values of ob
using another foreach()
, also your first foreach()
had some syntax error, have a look on my below answer. This should work for sure to get the values inside $weather->ob
<?php
// fetch Aeris API output as a string and decode into an object
$response = file_get_contents("https://api.aerisapi.com/observations/closest?p=:auto&format=json&radius=50mi&filter=allstations&limit=5&fields=id,ob.tempF,ob.dewpointF,ob.humidity,ob.windSpeedMPH,ob.windDir,ob.weather,ob.heatindexF,ob.feelslikeF&client_id=fRqZ7kEn97lvuYQlIFZ8y&client_secret=GKl5UydVJoSP7UDxmXWx5J8pegsFybclACCyVksr");
$json = json_decode($response);
foreach ($json->response as $weather)
{
echo '<pre>';
#var_dump($weather);
#print_r($weather->ob);
echo '</pre>';
foreach($weather->ob as $key=>$value){
if($key =='tempF'){
echo "$key = $value";
echo "<br/>";
}
}
}
?>
Basically you need to iterate on your $weather->ob to get the inner values. Let's say you need only the tempF value from the inner object then you can put an if a condition like above to print that only if you need all values inside the $weather->ob then just remove the condition