SimpleXMlement 개체에서 값 가져오기

이런 게 있어요.

$url = "http://ws.geonames.org/findNearbyPostalCodes?country=pl&placename="; $url .= rawurlencode($city[$i]);
$xml = simplexml_load_file($url); echo $url."n"; $cityCode[] = array(
'city' => $city[$i],
'lat' => $xml->code[0]->lat,
'lng' => $xml->code[0]->lng ); 

지네임에서 XML을 다운로드 받아야 합니다.내가 하면print_r($xml)다음과 같은 것이 있습니다.

SimpleXMLElement Object (
[code] => Array
(
 [0] => SimpleXMLElement Object

(

[postalcode] => 01-935

[name] => Warszawa

[countryCode] => PL

[lat] => 52.25

[lng] => 21.0

[adminCode1] => SimpleXMLElement Object

 (

 )

[adminName1] => Mazowieckie

[adminCode2] => SimpleXMLElement Object

 (

 )

[adminName2] => Warszawa

[adminCode3] => SimpleXMLElement Object

 (

 )

[adminName3] => SimpleXMLElement Object

 (

 )

[distance] => 0.0

) 

보시는 대로 하겠습니다.$xml->code[0]->lat오브젝트를 반환합니다.어떻게 하면 값을 얻을 수 있을까요?



질문에 대한 답변



문자열에 simpleXML 개체를 캐스팅해야 합니다.

$value = (string) $xml->code[0]->lat; 



마법 메서드 __toString()을 사용할 수도 있습니다.

$xml->code[0]->lat->__toString() 



XML 요소의 값이 부동 번호(위도, 경도, 거리)인 경우 다음을 사용할 수 있습니다.(float)

$value = (float) $xml->code[0]->lat; 

또한.(int)정수:

$value = (int) $xml->code[0]->distance; 



XML 요소의 값을 모르는 경우,

$value = (string) $xml->code[0]->lat;
if (ctype_digit($value)) {
// the value is probably an integer because consists only of digits } 

값이 숫자인지 아닌지를 판별할 필요가 있는 경우에 유효합니다.(string)항상 문자열을 반환하고is_int($value)돌아온다false




어레이는 오브젝트보다 사용하기 쉬워요.

Xml-Object를 변환합니다.

$xml = simplexml_load_file('xml_file.xml');
$json_string = json_encode($xml);
$result_array = json_decode($json_string, TRUE);