note 86862 modified in function.fsockopen by danbrown
| From: | danbrown@php.net | Date: | Thu, 06 Nov 2008 23:20:15 +0000 |
| Subject: | note 86862 modified in function.fsockopen by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-146263@lists.php.net to get a copy of this message | ||
[NOTE BY danbrown AT php DOT net: Updated version. Contains author-submitted bug fixes.]
Here is a way to get an array of cities / states for any zip code anywhere in the US. This example
uses a $_GET variable to specify which zip code, but you can get it from any source you wish. This
will return actual and acceptable zip code cities (according to USPS), but can be easily modified to
include just the actual city.
<?php
if($_GET['zip'])
{
if(!($fp = fsockopen('zip4.usps.com', 80, $errno, $errstr)))
echo 'Could not connect to USPS! Error number: ' . $errno . '(' . $errstr .
')';
else
{
$poststring =
"GET /zip4/zcl_3_results.jsp?zip5=" . $_GET['zip'] . "
HTTP/1.0\r\n" .
"Connection: close\r\n\r\n";
fputs($fp, $poststring);
$buffer = '';
while(!feof($fp))
$buffer .= fgets($fp, 128);
fclose($fp);
preg_match('/Actual City name(.*)/s', $buffer, $match);
$temp = explode('Not Acceptable', $match[1]);
// Capture city/state combination for all valid cities
preg_match_all('/headers="pre">(?:<b>)?([\w|\s]+), (\w+)/', $temp[0],
$acceptable, PREG_SET_ORDER);
$values = array();
foreach($acceptable as $value)
$values[] =
array
(
'city' => $value[1],
'state' => $value[2]
);
if(count($values) == 0)
echo 'Zip could not be found in the database!';
}
}
else
echo 'Please specify a zip!';
?>
--was--
Here is a slightly revised version of the USPS zip code city finder that includes some error
messages, as well as changed the $_GET['zip5'] variable into an easier to remember
$_GET['zip'] variable:
<?php
if($_GET['zip'])
{
if(!($fp = fsockopen('zip4.usps.com', 80, $errno, $errstr)))
echo 'Could not connect to USPS! Error number: ' . $errno . '(' . $errstr .
')';
else
{
$poststring =
"GET /zip4/zcl_3_results.jsp?zip5=" . $_GET['zip'] . "
HTTP/1.0\r\n" .
"Connection: close\r\n\r\n";
fputs($fp, $poststring);
$buffer = '';
while(!feof($fp))
$buffer .= fgets($fp, 128);
fclose($fp);
preg_match('/Actual City name(.*)/s', $buffer, $match);
$temp = explode('Not Acceptable', $match[1]);
// Capture city/state combination for all valid cities
preg_match_all('/headers="pre">(?:<b>)?([\w|\s]+), (\w+)/', $temp[0],
$acceptable, PREG_SET_ORDER);
$values = array();
foreach($acceptable as $value)
$values[] =
array
(
'city' => $value[1],
'state' => $value[2]
);
if(count($values) == 0)
echo 'Zip could not be found in the database!';
}
}
else
echo 'Please specify a zip!';
?>
http://php.net/manual/en/function.fsockopen.php