Reworked code to return in an array with the array IDs being zip, city and state.
CODE
/ ********************************************************************************
*****
*
* FILENAME: zip.php
* MODIFIED AND OPTIMIZED from http://www.zend.com//tips/tips.php?ozid=249&single=1
* MODIFIED BY MICHAEL THERRIEN
* 10/07/08
* Version 1.0
* http://www.michaeltherrien.com
* This script uses the free zipcode search engine at zipinfo.com to retrieve the city and state that a zipcode is associated with.
* If the script doesn't work, make sure that 'allow_url_fopen' is set to 1 (on) in your php.ini file.
* $city and $state are the variables it outputs
*
********************************************************************************
******/
<?
function get_zip_info($zip) { //Function to retrieve the contents of a webpage and put it into $pgdata
$pgdata =""; //initialize $pgdata
$fd = fopen("http://zipinfo.com/cgi-local/zipsrch.exe?zip=$zip","r"); //open the url based on the user input and put the data into $fd
while(!feof($fd)) {//while loop to keep reading data into $pgdata till its all gone
$pgdata .= fread($fd, 1024); //read 1024 bytes at a time
}
fclose($fd); //close the connection
if (preg_match("/is not currently assigned/", $pgdata)) {
$city = "N/A";
$state = "N/A";
}
else {
$citystart = strpos($pgdata, "Code</th></tr><tr><td align=center>");
$citystart = $citystart + 35;
$pgdata = substr($pgdata, $citystart);
$cityend = strpos($pgdata, "</font></td><td align=center>");
$city = substr($pgdata, 0, $cityend);
$statestart = strpos($pgdata, "</font></td><td align=center>");
$statestart = $statestart + 29;
$pgdata = substr($pgdata, $statestart);
$stateend = strpos($pgdata, "</font></td><td align=center>");
$state = substr($pgdata, 0, $stateend);
}
$zipinfo[zip] = $zip;
$zipinfo[city] = $city;
$zipinfo[state] = $state;
return $zipinfo;
}
if ( $_POST['zip'] == "" ) {
?>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="zip" maxlength="5" size="4">
<input type="submit" value="Find Zip Info">
</form>
<?
}
else {
$works = get_zip_info($_POST['zip']);
echo "Zip Code: ".$works[zip]."<br>City: ".$works[city]."<br>State: ".$works[state];
}
?>
Personaly I think it works better that way.
This post has been edited by engale: 7 Oct, 2008 - 09:05 PM