I am working on a PHP code for my social network, what I am planning to do is on user signup or profile update I will take there zipcode that they enter and use yahoo to lookup there lattitude and logitude from there zipcode I will then save these value to there user mysql table, this will be used later on to find users located within X amount of miles from them.
Here is my code so far to get this info before storing into DB
<?PHP
function yahoo_geo($location) {
$q = 'http://api.local.yahoo.com/MapsService/V1/geocode';
q .= '?appid=rlerdorf&location='.rawurlencode($location);
echo $q;
libxml_use_internal_errors(true);
$xml = simplexml_load_file($q);
if(!is_object($xml)) return false;
$ret['precision'] = (string)$xml->Result['precision'];
foreach($xml->Result->children() as $key=>$val) {
if(strlen($val)){
$ret[(string)$key] = (string)$val;
}
return $ret;
}
$_REQUEST['location'] = 32744; // my zip code
$a = yahoo_geo($_REQUEST['location']);
// set retunred data to some variables for storage into MySQL
$latitude = $a[Latitude];
$longitude = $a[Longitude];
// MySQL code will go here
// Output for demo
echo 'Lattitude' .$latitude. '<BR><BR>';
echo 'Longitude' .$longitude. '<BR><BR>';
?>
This works great except if a long. and lat. is not found it returns an error to the browser
Warning: simplexml_load_file(http://api.local.yahoo.com/MapsService/V1/geocode?appid=rlerdorf&location=some non zipcode) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\webserver\htdocs\test\geolocation\index.php on line 16
Note; I could make sure that zipcode is numeric only but I would rather not as yahoo will let me search with other fields as well, so If a user does not enter a zipcode I will make it use a city or state or even country at the worse case so every user should have some sort of longitude and lat. saved
Is there a good way to avoid the error showing or even better is there a way to detect id there is an error and if an error occurs I could insert a default value for that user?