PHP: Get zipcode for an Address

I needed a small php function that could take an address (which lacked a zip code) and fetch a best guess postal code for it. I had a database full of addresses with city and state, but no zip code. Thankfully, if you have enough information in your address to locate it with the Google maps geocoding service, you have enough information to get the zip code. If not the correct zip code, it should pull one that’s relatively close assuming you’ve specified the correct city and state in your address.

This is possible because the geocoding service will return matches with full address data available. If we assume that the first match is most likely the correct match, we can just extract it’s postal code. I’ve only tested this with US addresses, but it may work in other countries where Google can geocode an address.

/**
 * Uses Google Maps Geocoder (V3) to get postal code for an address.  Uses first address match.
 * @param String Address - Make sure to include at least the street address, city and state.
 * @return String - Zip code on success, blank if a zip code is failed to be retrieved.
 */
function zip_code_from_address($address)
{
   $ura = rawurlencode($address);
   $rurl = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&address=$ura";
   $dom = new DOMDocument();
   $res = $dom->loadXML(file_get_contents($rurl));
   if($res)
   {
      if($status = $dom->getElementsByTagName('status')->item(0))
      {
         if($status->nodeValue == 'OK')
         {
            //If status is OK, then at least one result should be here.
            $result = $dom->getElementsByTagName('result')->item(0);
            $postalcode = '';
            foreach($result->getElementsByTagName('address_component') as $comp)
            {
               if($comp->getElementsByTagName('type')->item(0)->nodeValue == 'postal_code')
               {
                  $postalcode = $comp->getElementsByTagName('short_name')->item(0)->nodeValue;
               }
            }
            return $postalcode;
         }
         else
         {
            return '';
         }
      }
   }
   else
   {
      return '';
   }
}

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>