Archive

Archive for July, 2011

Use PHP & YQL to find out what city a zip is from


<?php
$_GET['zip'] = '16601';
//Validate the zip
$zip = str_replace(" ", "", $_GET['zip']); //remove white-space
if (!ctype_alnum($zip)) {
    die("Enter alpha-numeric numbers only");
}
if (strlen($zip) > 7) {
    die("Zip query is too long");
}
$zip = urlencode($zip);
$url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20google.geocoding%20where%20q%3D%22$zip%22&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
$xml = file_get_contents($url);
$location = new SimpleXMLElement($xml);
//var_dump($xml);
//var_dump($location);
$status = (string)$location->results->json->Status->code;
if ($status !== '200') {
    die('Could not get location');
}
$country = (string)$location->results->json->Placemark->AddressDetails->Country->CountryName;
switch ($country) {
case "USA":
case "Canada":
    echo (string)$location->results->json->Placemark->address;
    break;

default:
    echo 'false';
}
Categories: experimental scripts