我有这样的东西:

$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相关的值转换为数组

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

    return $out;
}

其他回答

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

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

你可以用这个函数转换数组

function xml2array($xml){
$arr = array();

foreach ($xml->children() as $r)
{
    $t = array();
    if(count($r->children()) == 0)
    {
        $arr[$r->getName()] = strval($r);
    }
    else
    {
        $arr[$r->getName()][] = xml2array($r);
    }
}
return $arr;
}

您可以使用“{}”来访问您的属性,然后您可以按照自己的意愿进行操作。 保存或显示内容。

    $varName = $xml->{'key'};

从你的例子中,她就是代码

        $filePath = __DIR__ . 'Your path ';
        $fileName = 'YourFilename.xml';

        if (file_exists($filePath . $fileName)) {
            $xml = simplexml_load_file($filePath . $fileName);
            $mainNode = $xml->{'code'};

            $cityArray = array();

            foreach ($mainNode as $key => $data)        {
               $cityArray[..] = $mainNode[$key]['cityCode'];
               ....

            }     

        }

快速解决如果你赶时间。

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

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

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

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