I want to get a users city, state/province, country from a google geocode of their postal/zip code (canada/usa). I retrieve the data as JSON: https://developers.google.com/maps/documentation/geocoding/#JSON
The problem is that there is not always the same amount/order of 'address_components'. I was using just like: $geocodedinfo['results'][0]['address_components'][3]['short_name'];
But I soon realized that that will not always be province/state because sometimes google will add an extra element under 'address_components'.
Is there a way to parse the results just for the specifics I need (ie: City, State/Province, Country)?
EDIT I actually decode the JSON when I get it json_decode($result, true)
Array
(
[results] => Array
(
[0] => Array
(
[address_components] => Array
(
[0] => Array
(
[long_name] => V2X 2P6
[short_name] => V2X 2P6
[types] => Array
(
[0] => postal_code
)
)
[1] => Array
(
[long_name] => Maple Ridge
[short_name] => Maple Ridge
[types] => Array
(
[0] => locality
[1] => political
)
)
[2] => Array
(
[long_name] => Maple Ridge
[short_name] => Maple Ridge
[types] => Array
(
[0] => administrative_area_level_3
[1] => political
)
)
[3] => Array
(
[long_name] => Greater Vancouver Regional District
[short_name] => Greater Vancouver Regional District
[types] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[4] => Array
(
[long_name] => British Columbia
[short_name] => BC
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[5] => Array
(
[long_name] => Canada
[short_name] => CA
[types] => Array
(
[0] => country
[1] => political
)
)
)
[formatted_address] => Maple Ridge, BC V2X 2P6, Canada
[geometry] => Array
(
[bounds] => Array
(
[northeast] => Array
(
[lat] => 49.2214351
[lng] => -122.6577849
)
[southwest] => Array
(
[lat] => 49.219268
[lng] => -122.663613
)
)
[location] => Array
(
[lat] => 49.2202679
[lng] => -122.660587
)
[location_type] => APPROXIMATE
[viewport] => Array
(
[northeast] => Array
(
[lat] => 49.2217005303
[lng] => -122.6577849
)
[southwest] => Array
(
[lat] => 49.2190025697
[lng] => -122.663613
)
)
)
[types] => Array
(
[0] => postal_code
)
)
)
[status] => OK
)
You're going to have to loop over the results.
Most of the relevant PHP functions don't support multidimensional arrays, and the ones that do will be looping anyway.
You'll probably want something like this:
foreach ($geocodedinfo["results"] as $result) {
foreach ($result["address_components"] as $address) {
// Repeat the following for each desired type
if (in_array("country", $address["types"])) {
$country = $address["long_name"];
}
}
}
You can run the results through a foreach loop and get the data out you are looking for.
I'm taking a best guess at the meanings of the Google types, I may be off on those.
$translate = array(
'locality' => 'city',
'administrative_area_level_3' => 'area', // not sure what this one is
'administrative_area_level_2' => 'county', // regional district ?
'administrative_area_level_1' => 'state', // province
'country' => 'country',
'postal_code' => 'zip', // postal code
);
$address_components = array( );
foreach ($geocodedinfo['results'][0]['address_components'] as $component) {
$address_components[$translate[$component['type'][0]]] = $component['long_name'];
}
var_dump($address_components);
try looking at this, http://php.net/manual/en/control-structures.foreach.php it's for looping over arrays, you can do something like,
foreach ($result['results'][0]['address_components'] as $key => $val)
{
if (in_array('country', $result['results'][0]['address_components'][$key]['types'][0]))
{
echo $result['results'][0]['address_components'][$key]['long_name'];
}
}
Something like that should work
// parse the json response
$jsondata = json_decode($data,true);
$results = $jsondata['results'][0];
$addr =$results['formatted_address'];
This allows you to access the long formatted address
326 London Road, Newbury, Berkshire, West Berkshire RG14 2DA, UK
Related
Get 20 results of (example:School ) from google places api and i want to show photos on google map but some api results does not contain any image so how i can fix it. Error show: undefined index 'photos'.
if ($resp['status']=='OK') {
//Loop through get the multiple results
for ($i=0; $i < count($resp['results']) ; $i++) {
//Get the Important Data
$data['formatted_address'] = $resp['results'][$i]['formatted_address'];
$data['latitude'] = $resp['results'][$i]['geometry']['location']['lat'];
$data['longitude'] = $resp['results'][$i]['geometry']['location']
enter code here['lng'];
$data['icon'] = $resp['results'][$i]['icon'];
$data['name'] = $resp['results'][$i]['name'];
$data['height'] = $resp['results'][$i]['photos'][0]['height'];
$data['html_attributions'] = $resp['results'][$i]['photos'][0]
['html_attributions'][0];
$data['photo_reference'] = $resp['results'][$i]['photos'][0]
['photo_reference'];
$data['width'] = $resp['results'][$i]['photos'][0]['width'];
//Verify if Data Exist
if (!empty($data) && !empty ($data['latitude']) && !empty
($data['longitude'])) {
print_r($data);
}else{
echo "<h1 style=color:red;>Values Empty</h1>";
}
}//End for-loop
}else{
echo "<h1 style=color:red;>Status Error</h1>";
}
Get the result of schools from google places api the index[1] does not contain any image than how to show on map.
[results] => Array(
[0] => Array
(
[formatted_address] => Tariqabad Multan, Punjab, Pakistan
[geometry] => Array
(
[location] => Array
(
[lat] => 30.2073928
[lng] => 71.4530978
)
[viewport] => Array
(
[northeast] => Array
(
[lat] => 30.208742629893
[lng] => 71.454447629893
)
[southwest] => Array
(
[lat] => 30.206042970107
[lng] => 71.451747970107
)
)
)
[icon] =>
https://maps.gstatic.com/mapfiles/place_api/icons/school-71.png
[id] => de1405f04fffe5f2910789717344e513625aada3
[name] => Learner's Castle School Multan
[photos] => Array
(
[0] => Array
(
[height] => 730
[html_attributions] => Array
(
[0] => Faisal Mushtaq
)
[photo_reference] =>
CmRaAAAAvhDiC7bMqpf3F5lvLSUmDkv8aAqSF1AaC_EoeUhG
f40GCU3H0zaLOQZ96fRZxTJ9goxxh2C
CfJXtJyXfMOBBqPPsOAKenERrefpNwtdV07nDyPE62nSdz3aO7T1aQaMy
EhBQOTSeTEKvNxBCk5rxl7 FUGhQ9MSlemG_o0jxeYE9f0_RmtnQzrQ
[width] => 1296
)
)
[place_id] => ChIJqfKsD8IzOzkRomMlLG80aho
[plus_code] => Array
(
[compound_code] => 6F43+X6 Multan, Pakistan
[global_code] => 8J2H6F43+X6
)
[rating] => 5
[reference] => ChIJqfKsD8IzOzkRomMlLG80aho
[types] => Array
(
[0] => school
[1] => point_of_interest
[2] => establishment
)
)
[1] => Array
(
[formatted_address] => N Gulgasht Blvd, Basti Mehmood Kot,
Multan, Punjab 60000, Pakistan
[geometry] => Array
(
[location] => Array
(
[lat] => 30.2464553
[lng] => 71.483087
)
[viewport] => Array
(
[northeast] => Array
(
[lat] => 30.247805129893
[lng] => 71.484436829893
)
[southwest] => Array
(
[lat] => 30.245105470107
[lng] => 71.481737170107
)
)
)
[icon] =>
https://maps.gstatic.com/mapfiles/place_api/icons/school-71.png
[id] => 8648cd48c320f11b001a0eece814bd72abc07231
[name] => Zakariya Public School
[opening_hours] => Array
(
[open_now] => 1
)
[place_id] => ChIJ5c1N-YM0OzkRKKtxXEhilow
[plus_code] => Array
(
[compound_code] => 6FWM+H6 Multan, Pakistan
[global_code] => 8J2H6FWM+H6
)
[rating] => 4.4
[reference] => ChIJ5c1N-YM0OzkRKKtxXEhilow
[types] => Array
(
[0] => school
[1] => point_of_interest
[2] => establishment
)
)
[2] => Array
(
[formatted_address] => 17- Officers Colony, Officers Colony,
Multan, Punjab, Pakistan
[geometry] => Array
(
[location] => Array
(
[lat] => 30.2105142
[lng] => 71.4726681
)
[viewport] => Array
(
[northeast] => Array
(
[lat] => 30.211864029893
[lng] => 71.474017929893
)
[southwest] => Array
(
[lat] => 30.209164370107
[lng] => 71.471318270107
)
)
)
[icon] =>
https://maps.gstatic.com/mapfiles/place_api/icons/school-71.png
[id] => 8c809b4c5a4b8355899ddf6b6a7497bb8cb43be1
[name] => Jinnah Highs School System
[opening_hours] => Array
(
[open_now] => 1
)
[photos] => Array
(
[0] => Array
(
[height] => 1920
[html_attributions] => Array
(
[0] => A Google User
)
[photo_reference] =>
CmRZAAAAmQ8VIRfu9_s5UTrmBRwHpPWYuPjXWWcRj5KnWGwTy4yXo-
h2bWa8NSXrYSI8ukYD8nhfQRVxjxVKfWMxJlC4Xn8D9KBmoB7M9P
CZU5_XHvZ2heWSXPkqcGvjlcDiMalsEhA3VzcWjoDnL9Fs7Bs8PP
t4GhSePGS5CmCg0AXA8kEfl91iWotZgA
[width] => 2560
)
)
[place_id] => ChIJz4eKo_YzOzkRHvCbt43xkq8
[plus_code] => Array
(
[compound_code] => 6F6F+63 Multan, Pakistan
[global_code] => 8J2H6F6F+63
)
[rating] => 4.3
[reference] => ChIJz4eKo_YzOzkRHvCbt43xkq8
[types] => Array
(
[0] => school
[1] => point_of_interest
[2] => establishment
)
)
you should first check if photo key is exist in $resp['results'][$i] array by using isset function in php
for example
if(isset($resp['results'][$i]['photos']) && count($resp['results'][$i]['photos']) > 0)
{
// write your code
}
and also you should use phpenter code here count function to check $resp['results'][$i]['photos'] array has multi entry
so you can write $resp['results'][$i]['photos'][0] without have out of scope error
I am using PHP to convert a list of postcodes + County into latitude and longitude. I have tried using the google map api and the simplexml_load_file() function like so:
$url ="http://maps.googleapis.com/maps/api/geocode/xml?address=WS9+8NS,+West+Midlands&sensor=false";
$result = simplexml_load_file($url);
print"<pre>";
print_r($result);
Now this works fine as I am able to get the following:
SimpleXMLElement Object
(
[status] => OK
[result] => SimpleXMLElement Object
(
[type] => postal_code
[formatted_address] => Walsall, Walsall, West Midlands WS9 8NS, UK
[address_component] => Array
(
[0] => SimpleXMLElement Object
(
[long_name] => WS9 8NS
[short_name] => WS9 8NS
[type] => postal_code
)
[1] => SimpleXMLElement Object
(
[long_name] => Walsall
[short_name] => Walsall
[type] => Array
(
[0] => locality
[1] => political
)
)
[2] => SimpleXMLElement Object
(
[long_name] => Walsall
[short_name] => Walsall
[type] => postal_town
)
[3] => SimpleXMLElement Object
(
[long_name] => West Midlands
[short_name] => West Mids
[type] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[4] => SimpleXMLElement Object
(
[long_name] => United Kingdom
[short_name] => GB
[type] => Array
(
[0] => country
[1] => political
)
)
)
[geometry] => SimpleXMLElement Object
(
[location] => SimpleXMLElement Object
(
[lat] => 52.6030230
[lng] => -1.9175368
)
[location_type] => APPROXIMATE
[viewport] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 52.6013713
[lng] => -1.9188871
)
[northeast] => SimpleXMLElement Object
(
[lat] => 52.6040692
[lng] => -1.9161892
)
)
[bounds] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 52.6020654
[lng] => -1.9182516
)
[northeast] => SimpleXMLElement Object
(
[lat] => 52.6033751
[lng] => -1.9168247
)
)
)
)
)
Problem now is, how should I take out the first latitude / longitude and not the whole thing, I only need these two values.
Please note that the lat/long are dynamic as the address changes for each search.
From the print_r you can see the structure of the content. Then, it is a matter of following it.
This contains the values:
$result->result->geometry->location
So to print them separately, you can say:
print "lat: " . $result->result->geometry->location->lat;
print "lng: " . $result->result->geometry->location->lng;
All together:
$url ="http://maps.googleapis.com/maps/api/geocode/xml?address=WS9+8NS,+West+Midlands&sensor=false";
$result = simplexml_load_file($url);
print "lat: " . $result->result->geometry->location->lat . " <br/>";
print "lng: " . $result->result->geometry->location->lng . " <br/>";
Better to use their JSON API.
$url ="http://maps.googleapis.com/maps/api/geocode/json?address=WS9+8NS,+West+Midlands&sensor=false";
$result = file_get_contents($url);
print"<pre>";
$resultArray = json_decode($result, true);
print_r($result);
Then just access like an array!
e.g.
$resultArray['results']['geometry']['location']['lat']
$resultArray['results']['geometry']['location']['lng']
I would use cURL instead of file get contents as it gives more control. But this works fine.
I would also check the $resultArray before attempting to do anything with it.
This seems like such a rookie question but I'm just banging my head against the keyboard here and I can't find anything answered already that gets me moving forward.
Scenario is I'm trying to get the Lat/Lng of a zip code by geocoding it with Google Maps API. I've gotten the results back from Google Maps API as a JSON string and I've used json_decode to put it into a PHP array. But it looks likt it's an array of objects and i'm stumped on how I can drill down into the data to get my lat/lng value.
Here is the current road block... code then results:
<?php
$jsonData = '{"results":[{"address_components":[{"long_name":"33647","short_name":"33647","types":["postal_code"]},{"long_name":"Tampa","short_name":"Tampa","types":["locality","political"]},{"long_name":"Florida","short_name":"FL","types":["administrative_area_level_1","political"]},{"long_name":"United States","short_name":"US","types":["country","political"]}],"formatted_address":"Tampa, FL 33647, USA","geometry":{"bounds":{"northeast":{"lat":28.17150,"lng":-82.26235779999999},"southwest":{"lat":28.07291710,"lng":-82.42569910}},"location":{"lat":28.14343180,"lng":-82.33433749999999},"location_type":"APPROXIMATE","viewport":{"northeast":{"lat":28.17150,"lng":-82.26235779999999},"southwest":{"lat":28.07291710,"lng":-82.42569910}}},"types":["postal_code"]}],"status":"OK"}';
$phpArray = json_decode($jsonData);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
echo "<p>$key | $value</p>";
}
?>
Results:
stdClass Object ( [results] => Array ( [0] => stdClass Object ( [address_components] => Array ( [0] => stdClass Object ( [long_name] => 33647 [short_name] => 33647 [types] => Array ( [0] => postal_code ) ) [1] => stdClass Object ( [long_name] => Tampa [short_name] => Tampa [types] => Array ( [0] => locality [1] => political ) ) [2] => stdClass Object ( [long_name] => Florida [short_name] => FL [types] => Array ( [0] => administrative_area_level_1 [1] => political ) ) [3] => stdClass Object ( [long_name] => United States [short_name] => US [types] => Array ( [0] => country [1] => political ) ) ) [formatted_address] => Tampa, FL 33647, USA [geometry] => stdClass Object ( [bounds] => stdClass Object ( [northeast] => stdClass Object ( [lat] => 28.1715 [lng] => -82.2623578 ) [southwest] => stdClass Object ( [lat] => 28.0729171 [lng] => -82.4256991 ) ) [location] => stdClass Object ( [lat] => 28.1434318 [lng] => -82.3343375 ) [location_type] => APPROXIMATE [viewport] => stdClass Object ( [northeast] => stdClass Object ( [lat] => 28.1715 [lng] => -82.2623578 ) [southwest] => stdClass Object ( [lat] => 28.0729171 [lng] => -82.4256991 ) ) ) [types] => Array ( [0] => postal_code ) ) ) [status] => OK )
results | Array
status | OK
URL used to create the input JSON:
http://maps.googleapis.com/maps/api/geocode/json?address=33647&sensor=false
Looking for some help to pull out the Lat and Long values out into a PHP variable.
Thanks in advance!
Josh
The value of results is in fact another array - so you need to dig into the array to get the values you need.
This page (http://json.parser.online.fr/) might help you to visualize the data a bit more clearly.
Here's a terrible example with your data to demonstrate the depth (arrays as values):
<?php
$jsonData = '{"results":[{"address_components":[{"long_name":"33647","short_name":"33647","types":["postal_code"]},{"long_name":"Tampa","short_name":"Tampa","types":["locality","political"]},{"long_name":"Florida","short_name":"FL","types":["administrative_area_level_1","political"]},{"long_name":"United States","short_name":"US","types":["country","political"]}],"formatted_address":"Tampa, FL 33647, USA","geometry":{"bounds":{"northeast":{"lat":28.17150,"lng":-82.26235779999999},"southwest":{"lat":28.07291710,"lng":-82.42569910}},"location":{"lat":28.14343180,"lng":-82.33433749999999},"location_type":"APPROXIMATE","viewport":{"northeast":{"lat":28.17150,"lng":-82.26235779999999},"southwest":{"lat":28.07291710,"lng":-82.42569910}}},"types":["postal_code"]}],"status":"OK"}';
$phpArray = json_decode($jsonData,true);
print_r($phpArray);
foreach ($phpArray as $key => $value) {
if ( $key == "results") {
foreach ($value as $key2 => $value2) {
foreach ($value2 as $key3 => $value3) {
echo "<p>$key3 | $value3</p>";
}
}
}
}
?>
You'll need to dig down a couple of levels to find the ll data you want. This should point you in the right direction though.
On my page I have a number of registered users, each user has a postcode stored in their row in my table.
I'm wondering if its possible and if so how to get the postcode of my website visitors and then show them the nearest users going of the data in my table?
You can use HTML 5 Geolocation to ask them to provide their location to you. Then you could lookup what the nearest postal code is based on their longitude/latitude.
You can get free postal/zip data with long/lat for North America here:
http://geocoder.ca/?freedata=1
If you can determine the coordinates of the visiting user in an accurate way you could use the google reverse geocoding API to translate the coordinates to an address and use the zipcode from that address.
Determining accurate coordinates of a visitor could prove difficult though. You'll have to rely on a GeoLocation api like http://www.maxmind.com/app/php or do an implementation of the HTML5 GeoLocation API.
You need to populate latitude/longitude for each record, then use Google Maps to find out nearest users, I believe following links will help you out.
Get latitude and longitude based on location name with Google Autocomplete API
Google Maps Api v3 - find nearest markers
Interesting, building on what others have said, perhaps this example will help ;)
<?php
//example a google IP
$user_info = get_ip_info('74.125.224.72');
$google_info = get_google_data($user_info['latitude'],$user_info['longitude']);
$user = array_merge($user_info,$google_info);
//See below for result
print_r($user);
function get_google_data($long,$lat){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$long.','.$lat.'&sensor=true');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
curl_close($ch);
return json_decode($data,true);
}
function get_ip_info($ip = NULL){
if(empty($ip)) $ip = $_SERVER['REMOTE_ADDR'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://www.ipaddresslocation.org/ip-address-locator.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,array('ip'=>$ip));
$data = curl_exec($ch);
curl_close($ch);
preg_match_all('/<i>([a-z\s]+)\:<\/i>\s+<b>(.*)<\/b>/im',$data,$matches,PREG_SET_ORDER);
if(count($matches)==0)return false;
$return = array();
$labels = array(
'Hostname' => 'host',
'IP Country' => 'country',
'IP Country Code' => 'country_code',
'IP Continent' => 'continent',
'IP Region' => 'region',
'IP Latitude' => 'latitude',
'IP Longitude' => 'longitude',
'Organization' => 'organization',
'ISP Provider' => 'isp');
foreach($matches as $info){
if(isset($info[2]) && !is_null($labels[$info[1]])){
$return[$labels[$info[1]]]=$info[2];
}
}
return (count($return))?$return:false;
}
/**
* Result:
*
*
* Array
(
[host] => nuq04s07-in-f8.1e100.net
[country] => United States
[country_code] => USA
[continent] => North America
[region] => California
[latitude] => 37.4192
[longitude] => -122.0574
[organization] => Google
[isp] => Google
[results] => Array
(
[0] => Array
(
[address_components] => Array
(
[0] => Array
(
[long_name] => Sevryns Rd
[short_name] => Sevryns Rd
[types] => Array
(
[0] => route
)
)
[1] => Array
(
[long_name] => Mountain View
[short_name] => Mountain View
[types] => Array
(
[0] => locality
[1] => political
)
)
[2] => Array
(
[long_name] => Santa Clara
[short_name] => Santa Clara
[types] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[3] => Array
(
[long_name] => California
[short_name] => CA
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[4] => Array
(
[long_name] => United States
[short_name] => US
[types] => Array
(
[0] => country
[1] => political
)
)
[5] => Array
(
[long_name] => 94043
[short_name] => 94043
[types] => Array
(
[0] => postal_code
)
)
)
[formatted_address] => Sevryns Rd, Mountain View, CA 94043, USA
[geometry] => Array
(
[bounds] => Array
(
[northeast] => Array
(
[lat] => 37.4197948
[lng] => -122.0577433
)
[southwest] => Array
(
[lat] => 37.4175854
[lng] => -122.0590077
)
)
[location] => Array
(
[lat] => 37.4187254
[lng] => -122.0583059
)
[location_type] => APPROXIMATE
[viewport] => Array
(
[northeast] => Array
(
[lat] => 37.420039080292
[lng] => -122.05702651971
)
[southwest] => Array
(
[lat] => 37.417341119709
[lng] => -122.05972448029
)
)
)
[types] => Array
(
[0] => route
)
)
[1] => Array
(
[address_components] => Array
(
[0] => Array
(
[long_name] => Moffett Federal Airfield
[short_name] => Moffett Federal Airfield
[types] => Array
(
[0] => establishment
)
)
[1] => Array
(
[long_name] => Cummins Ave
[short_name] => Cummins Ave
[types] => Array
(
[0] => route
)
)
[2] => Array
(
[long_name] => Mountain View
[short_name] => Mountain View
[types] => Array
(
[0] => locality
[1] => political
)
)
[3] => Array
(
[long_name] => Santa Clara
[short_name] => Santa Clara
[types] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[4] => Array
(
[long_name] => California
[short_name] => CA
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[5] => Array
(
[long_name] => United States
[short_name] => US
[types] => Array
(
[0] => country
[1] => political
)
)
[6] => Array
(
[long_name] => 94043
[short_name] => 94043
[types] => Array
(
[0] => postal_code
)
)
)
[formatted_address] => Moffett Federal Airfield (NUQ), Cummins Ave, Mountain View, CA 94043, USA
[geometry] => Array
(
[bounds] => Array
(
[northeast] => Array
(
[lat] => 37.4298225
[lng] => -122.0375869
)
[southwest] => Array
(
[lat] => 37.4019577
[lng] => -122.0589996
)
)
[location] => Array
(
[lat] => 37.4199527
[lng] => -122.0584702
)
[location_type] => APPROXIMATE
[viewport] => Array
(
[northeast] => Array
(
[lat] => 37.4298225
[lng] => -122.0375869
)
[southwest] => Array
(
[lat] => 37.4019577
[lng] => -122.0589996
)
)
)
[types] => Array
(
[0] => airport
[1] => transit_station
[2] => establishment
)
)
[2] => Array
(
[address_components] => Array
(
[0] => Array
(
[long_name] => 94043
[short_name] => 94043
[types] => Array
(
[0] => postal_code
)
)
[1] => Array
(
[long_name] => Mountain View
[short_name] => Mountain View
[types] => Array
(
[0] => locality
[1] => political
)
)
[2] => Array
(
[long_name] => California
[short_name] => CA
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[3] => Array
(
[long_name] => United States
[short_name] => US
[types] => Array
(
[0] => country
[1] => political
)
)
)
[formatted_address] => Mountain View, CA 94043, USA
[geometry] => Array
(
[bounds] => Array
(
[northeast] => Array
(
[lat] => 37.464087
[lng] => -122.03599
)
[southwest] => Array
(
[lat] => 37.3857439
[lng] => -122.10842
)
)
[location] => Array
(
[lat] => 37.428434
[lng] => -122.0723816
)
[location_type] => APPROXIMATE
[viewport] => Array
(
[northeast] => Array
(
[lat] => 37.464087
[lng] => -122.03599
)
[southwest] => Array
(
[lat] => 37.3857439
[lng] => -122.10842
)
)
)
[types] => Array
(
[0] => postal_code
)
)
[3] => Array
(
[address_components] => Array
(
[0] => Array
(
[long_name] => Santa Clara
[short_name] => Santa Clara
[types] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[1] => Array
(
[long_name] => California
[short_name] => CA
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[2] => Array
(
[long_name] => United States
[short_name] => US
[types] => Array
(
[0] => country
[1] => political
)
)
)
[formatted_address] => Santa Clara, CA, USA
[geometry] => Array
(
[bounds] => Array
(
[northeast] => Array
(
[lat] => 37.484637
[lng] => -121.208178
)
[southwest] => Array
(
[lat] => 36.894155
[lng] => -122.202476
)
)
[location] => Array
(
[lat] => 37.2938907
[lng] => -121.7195459
)
[location_type] => APPROXIMATE
[viewport] => Array
(
[northeast] => Array
(
[lat] => 37.484637
[lng] => -121.208178
)
[southwest] => Array
(
[lat] => 36.894155
[lng] => -122.202476
)
)
)
[types] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[4] => Array
(
[address_components] => Array
(
[0] => Array
(
[long_name] => California
[short_name] => CA
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[1] => Array
(
[long_name] => United States
[short_name] => US
[types] => Array
(
[0] => country
[1] => political
)
)
)
[formatted_address] => California, USA
[geometry] => Array
(
[bounds] => Array
(
[northeast] => Array
(
[lat] => 42.0095169
[lng] => -114.131211
)
[southwest] => Array
(
[lat] => 32.5342071
[lng] => -124.4096195
)
)
[location] => Array
(
[lat] => 36.778261
[lng] => -119.4179324
)
[location_type] => APPROXIMATE
[viewport] => Array
(
[northeast] => Array
(
[lat] => 42.0095169
[lng] => -114.131211
)
[southwest] => Array
(
[lat] => 32.5342071
[lng] => -124.4096195
)
)
)
[types] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[5] => Array
(
[address_components] => Array
(
[0] => Array
(
[long_name] => United States
[short_name] => US
[types] => Array
(
[0] => country
[1] => political
)
)
)
[formatted_address] => United States
[geometry] => Array
(
[bounds] => Array
(
[northeast] => Array
(
[lat] => 90
[lng] => 180
)
[southwest] => Array
(
[lat] => -90
[lng] => -180
)
)
[location] => Array
(
[lat] => 37.09024
[lng] => -95.712891
)
[location_type] => APPROXIMATE
[viewport] => Array
(
[northeast] => Array
(
[lat] => 49.38
[lng] => -66.94
)
[southwest] => Array
(
[lat] => 25.82
[lng] => -124.39
)
)
)
[types] => Array
(
[0] => country
[1] => political
)
)
)
[status] => OK
)
*/
?>
I am trying to extract the postal code from the Google Geocode v3 API XML Response. The difficulty I am having is that sometimes the postal_code value is contained in the 6th address_element and sometimes in the 7th. Here is the XML response that I am working with and in this sample response you can see that the postal_code is the 6th element of the address_component array:
SimpleXMLElement Object
(
[status] => OK
[result] => Array
(
[0] => SimpleXMLElement Object
(
[type] => street_address
[formatted_address] => 177 Church St, Toronto, ON M5C 2G5, Canada
[address_component] => Array
(
[0] => SimpleXMLElement Object
(
[long_name] => 177
[short_name] => 177
[type] => street_number
)
[1] => SimpleXMLElement Object
(
[long_name] => Church St
[short_name] => Church St
[type] => route
)
[2] => SimpleXMLElement Object
(
[long_name] => Toronto
[short_name] => Toronto
[type] => Array
(
[0] => locality
[1] => political
)
)
[3] => SimpleXMLElement Object
(
[long_name] => Toronto
[short_name] => Toronto
[type] => Array
(
[0] => administrative_area_level_2
[1] => political
)
)
[4] => SimpleXMLElement Object
(
[long_name] => Ontario
[short_name] => ON
[type] => Array
(
[0] => administrative_area_level_1
[1] => political
)
)
[5] => SimpleXMLElement Object
(
[long_name] => Canada
[short_name] => CA
[type] => Array
(
[0] => country
[1] => political
)
)
[6] => SimpleXMLElement Object
(
[long_name] => M5C 2G5
[short_name] => M5C 2G5
[type] => postal_code
)
)
[geometry] => SimpleXMLElement Object
(
[location] => SimpleXMLElement Object
(
[lat] => 43.6547363
[lng] => -79.3763746
)
[location_type] => RANGE_INTERPOLATED
[viewport] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 43.6533849
[lng] => -79.3777345
)
[northeast] => SimpleXMLElement Object
(
[lat] => 43.6560829
[lng] => -79.3750365
)
)
[bounds] => SimpleXMLElement Object
(
[southwest] => SimpleXMLElement Object
(
[lat] => 43.6547315
[lng] => -79.3763964
)
[northeast] => SimpleXMLElement Object
(
[lat] => 43.6547363
[lng] => -79.3763746
)
)
)
)
I haven't tried this, but I think it should work.
$address = $array->result[0]->address_component;
$postal_code = '';
foreach($address as $adr){
if($adr->type == 'postal_code'){
$postal_code = $adr->long_name;
}
}