PHP – Verify ZipCode using USPS service

United state postal service (USPS) is an independent agency of the United States federal government responsible for providing postal service in the United States. USPS has APIs you can use this API to validate the Zip Code.

How to use this:

You have to create your account on USPS. Once you will done with account creation you will get an email with your username and password.

http://production.shippingapis.com/ShippingAPI.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID=” xxxxxxxxxxxx”> 90210

But soon you will find that this URL will on on browser. You can’t access this URL, you will get error “URL not format properly”. Please find the solution below for this.

$input_xml = <<<EOXML
               <CityStateLookupRequest USERID=" 850BIGMO0558">
               <ZipCode ID= "0">
               <Zip5>$zipcode</Zip5>
               </ZipCode>
              </CityStateLookupRequest>
EOXML;

        $fields = array(
                'API' => 'CityStateLookup',
                'XML' => $input_xml
            );
        $url = 'http://production.shippingapis.com/ShippingAPITest.dll?' . http_build_query($fields);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $data = curl_exec($ch);
        curl_close($ch);

    // Convert the XML result into array
    $array_data = json_decode(json_encode(simplexml_load_string($data)), true);
    echo  $array_data['ZipCode']['State'];

It will return the state name.