Showing posts with label Using zip code get city state name using php. Show all posts
Showing posts with label Using zip code get city state name using php. Show all posts

Friday, December 7, 2012

Using zip code get city state name using php

<?
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];
}
?>

Popular Posts