Address Standardization & Verification with USPS web tools and PHP


Before using this code you will need to sign up for an account with USPS webtools here.

Class, save as ‘usps_address_class.php’


account . '">
'; $xml .= '' . $this->address1 . ''; $xml .= '' . $this->address2 . ''; $xml .= '' . $this->city . ''; $xml .= '' . $this->state . ''; $xml .= '' . $this->zip . ''; $xml .= '
'; if ($this->ship_address2 <> ''){ //shipping address $xml .= '
'; $xml .= '' . $this->ship_address1 . ''; $xml .= '' . $this->ship_address2 . ''; $xml .= '' . $this->ship_city . ''; $xml .= '' . $this->ship_state . ''; $xml .= '' . $this->ship_zip . ''; $xml .= '
'; } $xml .= ''; return $xml; } function submit_request() { $ch = curl_init($this->url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "API=Verify&XML=" . $this->toXML()); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); $result = curl_exec($ch); $error = curl_error($ch); if(empty($error)) { return $result; }else{ die(curl_error($ch)); } } } ?>

And a sample page accessing it:


address1 = 'suite 321';
$uspsRequest->address2 = '1600 Pennsylvania Ave NW';
$uspsRequest->city = 'Washington';
$uspsRequest->state = 'DC';
$uspsRequest->zip = '20500';
/*
//optional second address
$uspsRequest->ship_address1 = '';
$uspsRequest->ship_address2 = '';
$uspsRequest->ship_city = '';
$uspsRequest->ship_state = '';
$uspsRequest->ship_zip = '';
*/

$result = $uspsRequest->submit_request();

if (!empty($result)){
		$xml = new SimpleXMLElement($result);
	}else{
		die;
	}

	
if(isset($xml->Address[0]->Error)) { echo ' Error Address 1';}
if(isset($xml->Address[1]->Error)) { echo ' Error Address 2';}

echo $xml->Address[0]->Address2 . ' ' . $xml->Address[0]->Address1 ;
echo '
'; echo $xml->Address[0]->City. ' ' . $xml->Address[0]->State . ' ' . $xml->Address[0]->Zip5; echo '
'; echo $xml->Address[1]->Address2 . ' ' . $xml->Address[1]->Address1 ; echo '
'; echo $xml->Address[1]->City. ' ' . $xml->Address[1]->State . ' ' . $xml->Address[1]->Zip5; ?>

8 responses to “Address Standardization & Verification with USPS web tools and PHP”

  1. Howdy! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Many thanks!

  2. Awesome. I’m trying to get this incorporated into my e-Commerce store to make shopping easier :-).

    Appreciate it!