USPS Web Tools for Address Validation, the tl;dr version

If you just want to know how the hell to get up and past the scripted tests and get on the live server, this post is for you. It goes like so:

The PHP I’m using is this:

<ZipCodeLookupRequest USERID=”xxxxxxxxxxx”>
<Address ID=”0”><Address1></Address1>
<Address2>6406 Ivy Lane</Address2>
//get the response from the USPS
$newurl = $url . urlencode($msg);
$xml = $newurl;
$parser = xml_parser_create();
// open a file and read data
$fp = fopen($xml, ‘r’);
$xmldata = fread($fp, 4096);

Once you’ve passed the testing, or if you’d rather do it as more a of live development sort of thing, the $msg block would look similar to this:

<ZipCodeLookupRequest USERID=”xxxxxxxxxxxx”>
<Address ID=”0”><FirmName></FirmName><Address1>’ . $shipAddress2 . ‘</Address1>
<Address2>’ . $shipAddress1 . ‘</Address2>
<City>’ . $shipCity . ‘</City><State>’ . $shipState . ‘</State>

Here, you are passing the address variables into the xml query (notice the FirmName tags – you will be using these once you are live, and they are required tags.) My Address 1 and Address 2 fields are reversed, as the form that uses these was initially written this way, and it was easier to switch these variables than several fields and labels on the form. If you can trust that the data being passed in will be clean, you could pass in $_POST variables, as well. In my case, I do a strtoupper on it, which is why they are not the $POST variables.

Don’t forget that it’s on you to provide error handling if the validation fails. You can see one way of doing it below, in the first Web Tools post. The easiest way I found essentially involves checking the tags for error values when the response is received.

This was developed in version 5-something of PHP. As far as I know, none of the PHP is version-specific to anything older than version 3. If that won’t work with your webhost, I suggest you find a new one.

Leave a Reply

Your email address will not be published. Required fields are marked *

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