Reputation: 518
I'm trying to extract data from an external url using json in PHP using the following code:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=37.76893497,-122.42284884&sensor=false";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo $json_data["formatted_address"];
?>
however, I get nothing on my page. in fact, i get this error:
Notice: Undefined index: formatted_address on line 7
is there something I'm missing?
any help would be greatly appreciated.
Upvotes: 1
Views: 5645
Reputation: 101
'formatted_address'
is a key of the main array 'results'
, so you should loop $json_data['results']
and search for the key 'formatted_address'
.
Upvotes: 2
Reputation: 7662
You are not providing proper INDEX
. Proper INDEX
is $json_data['results'][0]['formatted_address'];
for 1st result.
Use foreach
loop to print all address.
Try
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=37.76893497,-122.42284884&sensor=false";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
foreach($json_data['results'] as $item)
{
echo $item['formatted_address']."<br />";
}
Upvotes: 1