mercredi 7 janvier 2015

PHP if else statement testing whether api php field is empty

I am attempting to get the city attribute out of an ip geolocation api. Sample of what is returned from the api:


{"as":"AS38484 Virgin Broadband VISP","city":"Adelaide","country":"Australia","countryCode":"AU","isp":"iseek Communications","lat":-27,"lon":133,"org":"iseek Communications","query":"1.178.0.144","region":"","regionName":"","status":"success","timezone":"","zip":""}


My code:



$query = '{"as":"AS38484 Virgin Broadband VISP","city":"Adelaide","country":"Australia","countryCode":"AU","isp":"iseek Communications","lat":-27,"lon":133,"org":"iseek Communications","query":"1.178.0.144","region":"","regionName":"","status":"success","timezone":"","zip":""}'
$query = @unserialize($query);
if($query && $query['status'] == 'success') {
if(!empty($query['city'])) {
$city = $query['city'];
// routine that uses $city gets called
} else {
$lat = $query['lat'];
$lon = $query['lon'];
// routine that uses $lat, $lon gets called
}
}


Basically, the if(!empty($query['city'])) is not behaving as expected (not that I would really know, I have been using PHP for that last week). I have also attempted setting $city before the if statement and then testing if($city != '').


Note: the reason for the differentiation between city and lat/lon is the weather api I am querying prefers city but not every ip is able to provide one.


Thanks


Aucun commentaire:

Enregistrer un commentaire