Reputation: 31
I'm new to JSON and parsing. I get the following results when requesting an elevation from the Google Elevation API.
{
"status": "OK",
"results": [ {
"location": {
"lat": 39.7391536,
"lng": -104.9847034
},
"elevation": 1608.8402100
} ]
}
When parsing, I don't know how to effectively reference the elevation using the json_decode results. My abridged code is below:
$json_string = file_get_contents($url);
$parsed_json = json_decode($json_string);
$geoElevation = $parsed_json->{'elevation'};
Can anyone tell me why I can't access the "elevation" value using the above?
Upvotes: 3
Views: 1037
Reputation: 49877
Try this:
$json_string = file_get_contents($url);
$parsed_json = json_decode($json_string);
echo $parsed_json->results[0]->elevation;
or if you prefer using array:
$json_string = file_get_contents($url);
$parsed_json = json_decode($json_string, TRUE);
echo $parsed_json['results'][0]['elevation'];
The second argument:
When TRUE, returned objects will be converted into associative arrays. from the json_encode manual
Upvotes: 4
Reputation: 145482
You should use print_r($parsed_json)
to get a better visualization of your data structure:
$parsed_json
(
[status] => OK
[results] => Array
(
[0] => Array
(
[location] => Array
(
[lat] => 39.739153600000001631542545510456
[lng] => -104.98470340000000078362063504755
)
[elevation] => 1608.8402100000000700674718245864
)
)
)
This is an array, which you get by using json_decode($json_string, TRUE);
. That makes it easier to traverse the entries.
In your case you want:
print $parsed_json["results"][0]["elevation"];
Normally you would want to foreach
over the numeric levels. But if you only expect one result, then [0]
is perfectly fine to use.
Upvotes: 3