2015-01-07 2 views
0

ip geolocation api에서 city 속성을 가져 오려고합니다. 이 API에서 반환 무엇 샘플 : PHP if else php 필드가 비어 있는지 테스트합니다.

내 코드

{"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 = '{"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 
    } 
} 

기본적으로, if(!empty($query['city']))가 예상대로 작동하지 않는이 (내가 아는 정말 것이라고, 내가 사용하고 있지 PHP는 지난 주). 또한 if 문 앞에 $city을 설정하고 if($city != '')을 테스트하려고했습니다.

질문 : 조건 조합을 찾지 못하고 도시 속성을 city으로 설정합니까? 도시 속성이 없으면 else 부분을 건너 뛰고 lat/lon을 설정하지 않습니다.

참고 : citylat/lon 사이의 차별에 대한 이유는 모든 IP 하나를 제공 할 수있는 날씨 내가 쿼리하고 API를 city을 선호하지만,하지 않습니다.

감사

+0

또한 무엇이 질문입니까? – Rizier123

+0

세미콜론이 코드에 있습니다. :) 도시 속성을 찾을 수없는 문제는 미안합니다. – Lanzafame

답변

1

두 가지 문제 :

1) 당신은 당신이와 함께 필드에 액세스 할 객체에 직렬화 것이기 때문에 JSON 데이터

2) 문자열을 비 일렬 화하는 json_decode를 사용 할 필요가

$query->city; 

not

$query['city']; 
2

$ 쿼리는 unserialize 호출하기 전에 '@'를 사용하지 않은 경우에 당신이 그것을 볼 것, 직렬화 된 PHP 배열이 아닙니다. JSON처럼 보이므로 json_decode 일 것입니다.

0

@ kao3991 및 @andrew는 데이터가 직렬화 된 배열이 아니라 JSON이라고 말합니다. 이것을 시도하십시오 :

$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 = json_decode($query, true); 
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 
    } 
}