U.S.P.S. Address Validation

From JacobAllred

Jump to: navigation, search

The United States Postal Services provides address validation for non-bulk uses via their web service.

Be aware that it has a few quirks, the biggest being that Address1 is actually what most people call Address2 (suite/apartment number). Weird, eh?

Sample PHP

<?php
 
include_once('class_http.php');
 
function validateAddress(){
	$xmlstr = <<<XML
<AddressValidateRequest USERID="XXXXXXXX">
	<Address ID="0">
		<Address1></Address1>
		<Address2></Address2>
		<City></City>
		<State></State>
		<Zip5></Zip5>
		<Zip4></Zip4>
	</Address>
</AddressValidateRequest>
XML;
 
	$xml = new SimpleXMLElement($xmlstr);
	$h = new http();
 
	// Populate Address
	$xml->Address->Address2 = '8060 south 615 east';
	$xml->Address->City = 'sandy';
	$xml->Address->State = 'ut';
	$xml->Address->Zip5 = '84047';
 
	// Prepare for XML call
	$h->xmlrequest = $xml->asXML();
 
	$output = str_replace(array("\n",'<?xml version="1.0"?>',"\t",),array('','',''),$xml->asXML());
	$url = 'http://Production.ShippingAPIs.com/ShippingAPI.dll?API=Verify&XML='.urlencode($output);
 
	// Submit data and get results
	$h->fetch($url,0,'','','','GET');
 
	print_r($h->body);die();
 
	// Put results into XML object
	$xml = new SimpleXMLElement($h->body);
 
	return $xml;
}
 
$xml = validateAddress();
print_r($xml);
 
?>
Personal tools