What I'm trying to do is pull specific data from Google Geocoding results in XML form. Eventually what I'm aiming for is a space where the user can enter their zip/postal code and the website will automatically pull their city/state/country/and coords, but right now I'm just testing to see if I can get it to work.
Here's the code I have so far:
$postcode = 11212; // zip code that will be looked up. Eventually I'll have a user-input the zip code, but for testing purposes this will suffice
$request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$postcode."&sensor=false";
$xml = simplexml_load_file($request_url) or die("url not loading");
$status = $xml->status;// GET the request status as google's api can return several responses
if ($status=="OK") {
foreach($xml->result->address_component as $address_component){
if(in_array("country", $address_component->type)){
$country = $address_component->long_name;
continue;
} elseif(in_array('locality', $address_component->type)){
$city = $address_component->long_name;
}
}
}
echo "$country";
echo "$city";
For those who haven't seen the results of the Geocode XML, here's what it looks like:
https://maps.googleapis.com/maps/api/geocode/xml?address=11212&sensor=false
I've been stuck here for ages and I feel like I'm going insane trying to figure out what I'm doing wrong. I know it's probably something simple, or I'm just making a silly mistake haha, but I figured it was time to ask for help.
So what am I doing wrong here? Thanks for the help, everyone :)
$address_component->typeas an argument toin_array(), you need to typecast it to array using(array) $address_component->type. Then it should work as expected. But I strongly recommend to configure your php.ini to show errors and warnings. Goodluck!