#!/usr/local/bin/php
function get_tag_data_r($tags,$string,$tag_data) {
//homebrew XML parser-like thingy
//recursively get data between an XML tags
//we use this to parse the output from the USPS
$num_tags=count($tags);
if ($num_tags!=1) {
$num_tags_i=count($tags[0]);
for ($i=0;$i<$num_tags_i;$i++) {
$tag_i=preg_replace("/<|>/","",$tags[0][$i]);
$string_i=preg_replace("/(.*?)(<$tag_i>)(.*?)(<\/$tag_i>)(.*)/is","\${3}",$string);
$tag_data=get_tag_data_r(array_slice($tags,1),$string_i,$tag_data);
}
} else {
$num_tags_j=count($tags[0]);
for ($j=0;$j<$num_tags_j;$j++) {
$tag=preg_replace("/<|>/","",$tags[0][$j]);
$tag_data_j[]=preg_replace("/(.*?)(<$tag>)(.*?)(<\/$tag>)(.*)/is","\${3}",$string);
}
$tag_data[]=$tag_data_j;
}
return $tag_data;
}
//*****The meat/tofu of the program is below*****
//form the Request to ZipCodeLookup w/an address
//**You have to use your own username and password**
$url='http://testing.shippingapis.com/ShippingAPITest.dll?API=ZipCodeLookup&XML=';
$msg='6406 Ivy LaneGreenbeltMD';
//get the response from the USPS
$newurl = $url . urlencode($msg);
echo "-We say to the USPS-\n";
echo "$newurl\n\n";
$contents=file_get_contents($newurl);
echo "-The USPS says-\n";
echo "$contents\n\n";
//handle the expected XML output containted in $contents with the function defined above:
//
//**The test server only returns Errors, so we're going to strip stuff out of the XML Error**
//
//This function was built really fast and does not handle a lot of stuff (like attributes)
//but it is more than what I found when I started so I'm passing it along. It basically
//just lets you grab stuff in an XML document that you can easily navigate to -> ,
// -> , and -> in this example. Specifying at
//the higher level is actually optional here since ,, and are unique.
//
$tag_data=get_tag_data_r(array(array(""),array("","","")),$contents,array());
echo "-We parse the XML Error-\n";
echo ":\t{$tag_data[0][0]}\n";
echo ":\t{$tag_data[0][1]}\n";
echo ":\t{$tag_data[0][2]}\n";
?>