Reputation: 1127
I have a strange problem. My conditional isn't working:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://maps.googleapis.com/maps/api/geocode/json? address='.urlencode($address).'&sensor=true');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close ($ch);
if($result !== null) {
$result = @json_decode($result, true);
$result = @$result['results'][0]['address_components'];
foreach($result as $key => $value) {
if($value['types'][0] == 'administrative_area_level_2')
return $value['long_name'];
}
} else {
throw new Exception('unable to look up the county');
}
I tried
if($result)
if($result != null)
if($result != '')
if(!empty($result))
if(isset($result))
neither one worked, script always goes inside the block, but the value of $result is null, I can see it through xdebug. Why is this happening?
edit:
here's a screenshot
here's what var_dump shows:
string '{ "results" : [], "status" : "ZERO_RESULTS" } ' (length=52)
This fixed it:
$result = @json_decode($result, true);
if(!empty($result['results'])) {
Upvotes: 0
Views: 85
Reputation: 410
I pasted your code an ran it with an address.
$result
was not json but html because the url is invalid (404).
json_decode
returned null
because the string could not be decoded.
At least two suggested modifications:
1 - In the url remove the space between ...json?
and address=...
2 - Use json_last_error
and/or check return value of json_decode
to see if json was properly decoded.
http://php.net/manual/en/function.json-last-error.php
Upvotes: 0
Reputation: 21130
Have you looked into the function is_null()
?
if(!is_null($result)) { ... }
Upvotes: 1
Reputation: 11984
Try this..May be its because of spaces.. also echo strlen($result);
after your curl_exec will help you to check if the result is empty or not.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://maps.googleapis.com/maps/api/geocode/json? address='.urlencode($address).'&sensor=true');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($ch);
curl_close ($ch);
if(trim($result)!='') {
$result = @json_decode($result, true);
$result = @$result['results'][0]['address_components'];
foreach($result as $key => $value) {
if($value['types'][0] == 'administrative_area_level_2')
return $value['long_name'];
}
} else {
throw new Exception('unable to look up the county');
}
Upvotes: 0
Reputation: 2399
Try adding a
var_dump($result);
die;
Right after the curl response, and do that for one you know should be null and them examine what the result is? It might not be returning null ever.. Remember the value "" is not a NULL value, it is a "" value.
Upvotes: 1