使用SimpleXML在PHP中迭代XML数据

时间:2015-02-07 00:23:35

标签: php xml parsing

我有以下简单XML数据:

  [Listeners] => 37
            [listener] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [IP] => 0.0.0.1
                            [UserAgent] => curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.16.2.3 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
                            [Connected] => 1236
                            [ID] => 120
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [IP] => 0.0.0.2
                            [UserAgent] => curl/7.19.7 (i386-redhat-linux-gnu) libcurl/7.19.7 NSS/3.16.2.3 Basic ECC zlib/1.2.3 libidn/1.18 libssh2/1.4.2
                            [Connected] => 1235
                            [ID] => 121
                        )

我想显示[IP]。

所以我有这个PHP脚本:

<?php

$url = "http://admin:password@media.xseu.net/admin/listclients?mount=/FavoriteFM";
$xml = simplexml_load_file($url);
echo "<pre>";
print_r($xml);
 $IP = $xml->listener->IP;
 echo $IP[0];

?>

但它没有用。如何以正确的方式显示IP?

3 个答案:

答案 0 :(得分:2)

$url = "http://admin:password@media.xseu.net/admin/listclients?mount=/FavoriteFM";
$xml = simplexml_load_file($url);
$IP = $xml->source->listener;
    foreach($IP as $row){
      echo $row->IP;
    }

您将获得阵列的所有IP。

答案 1 :(得分:1)

只需更改此行:

(你只是忘记了第一级资源)

$IP = $xml->listener->IP;

到此:

$IP = $xml->source->listener->IP;
        //^^^^^^^^ See here

答案 2 :(得分:0)

这应该适合你:

foreach($xml->source->listener as $ip) 
    echo $ip->IP . "<br />";