H.HISTORY
H.HISTORY

Reputation: 518

get data from external url using php json?

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

Answers (3)

Simone Torrisi
Simone Torrisi

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

Hassaan
Hassaan

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

user4628565
user4628565

Reputation:

try this way,

echo $json_data['results'][0]['formatted_address'];

Upvotes: 1

Related Questions