我有这样的东西:

$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
);

它应该从geonames下载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->代码[0]->lat,它返回一个对象。我怎样才能得到这个值?


当前回答

快速解决如果你赶时间。

将Xml-Object转换为数组(或对象),

function loadXml2Array($file,$array=true){
   $xml = simplexml_load_file($file);   
 
   $json_string = json_encode($xml);    
   return json_decode($json_string, $array);
}

其他回答

如果您知道XML元素的值是一个浮点数(纬度、经度、距离),则可以使用(float)

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

同样,(int)表示整数:

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

您必须将simpleXML Object转换为字符串。

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

尝试当前(- > xml代码美元[0]- > lat)

它返回数组当前指针下的element,它是0,所以你会得到value

快速解决如果你赶时间。

将Xml-Object转换为数组(或对象),

function loadXml2Array($file,$array=true){
   $xml = simplexml_load_file($file);   
 
   $json_string = json_encode($xml);    
   return json_decode($json_string, $array);
}

这个函数总是帮助我将xml相关的值转换为数组

function _xml2array ( $xmlObject, $out = array () ){
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? _xml2array ( $node ) : $node;

    return $out;
}