1

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.

3
  • var_dump($json) should help you and us both :) Commented Aug 6, 2015 at 6:17
  • @Jigar, thanks, var_dump($json) prints the entire the content of the URL on my page now. Commented Aug 6, 2015 at 6:21
  • Please update your question with var_dump($json)'s output. Commented Aug 6, 2015 at 6:26

3 Answers 3

2

'formatted_address' is a key of the main array 'results', so you should loop $json_data['results'] and search for the key 'formatted_address'.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried Chandu's suggestion and still nothing being printed on my page! a blank page!
I tried that code and it works, is php configured well?
1

try this way,

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

1 Comment

still nothing! a blank page!
1

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 />";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.