Reputation: 13
This is my first time working with a JSON and I am clearly getting something wrong, Im just very unsure what it is.
I have looked up how to parse a simple json, but I think its the deeper levels of a google geocode that may be throwing me off.
Heres how I am trying to obtain my values:
$getJSON = "http://maps.googleapis.com/maps/api/geocode/json?address=" . str_replace(" ", "", $_POST['postcode']) . "&sensor=false";
$contentJSON = file_get_contents($getJSON);
$Geocode_array = json_decode($contentJSON, true);
$lat = $Geocode_array[results][address_components][geometry][location][lat];
$lng = $Geocode_array[results][address_components][geometry][location][lng];
and if required I can post the json code.
Upvotes: 1
Views: 2180
Reputation: 162851
Try quoting your array keys. Without the quotes, PHP is assuming those keys are undefined constants. Additionally, you've also not traversed the JSON result quite correctly. Try this:
$lat = $Geocode_array['results'][0]['geometry']['location']['lat'];
$lng = $Geocode_array['results'][0]['geometry']['location']['lng'];
The Google Maps API gives you multiple results in an array. I'm referencing the first one in the code immediately above (index 0
). A helpful thing to do during development is to print associative arrays to the PHP output buffer using print_r()
. That's how I figured it out.
print_r($Geocode_array);
Upvotes: 3