Finding the state of a zipcode using reverse lookup with Google Geocoding API

Here’s a code snippet if you need to run a reverse lookup on a zipcode to identify which state it is located in.  Google Geocoding API version 3 is the latest at this time of post, and there’s no longer an API key required to make the geocoding call! (sorry about the overlapping across the right sidebar, but copy n’ paste still works.)

$zipcode = "20002";

$geourl = "$zipcode&sensor=false";

// Transfer the XML content from Google
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $geourl);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$xmlContent = trim(curl_exec($c));

// load the XML content into a SimpleXML object for ease of acccess
$xmlObject = simplexml_load_string($xmlContent);

print header("Content-type: text/plain");
// If you want to see all the values you can use inside the object, uncomment the next line.


if ( $xmlObject->status == "OK") {
   for ($addr_comp_count=0; $addr_comp_count < sizeof($xmlObject->result->address_component); $addr_comp_count++) {
     if ( $xmlObject->result->address_component[$addr_comp_count]->type[0] == "administrative_area_level_1" ) {
       $state = $xmlObject->result->address_component[$addr_comp_count]->short_name;

print $state ;
This entry was posted in Programming, Web/Tech. Bookmark the permalink.