如何从XML文档中提取数据

时间:2015-04-30 10:23:03

标签: php xml

 $xml=simplexml_load_string($lists) or die("Error: Cannot create object");
print_r($xml);

给出:

SimpleXMLElement Object ( 
    [list] => Array ( 
        [0] => SimpleXMLElement Object ( 
            [@attributes] => Array ( 
                [id] => 8 
                [name] => #1 
                [subscriber_count] => 210 
                [display_name] => Display name 
            ) 
        ) 
        [1] => SimpleXMLElement Object ( 
            [@attributes] => Array ( 
                [id] => 9 
                [name] => #2 No External Promotions 
                [subscriber_count] => 2242 
                [display_name] => Display name 
            ) 
        ) 
        [2] => SimpleXMLElement Object ( 
            [@attributes] => Array ( 
                [id] => 939036 
                [name] => #1 No Internal Promotions 
                [subscriber_count] => 3301 
                [display_name] => Display name 
        ) 
    )
)

如何使用foreach循环提取“id”和其他信息。

1 个答案:

答案 0 :(得分:1)

要访问您需要了解的有关xml结构的数据。正如我从转储中看到的那样,您可以访问所有第一个列表节点的属性,如下所示:

$xml=simplexml_load_string($lists) or die("Error: Cannot create object");
foreach($xml->list[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

对于所有节点示例:

foreach($xml->list as $list){
    echo (string) $list, "\n";
    foreach($list->attributes() as $a => $b) {
       echo $a,'="',$b,"\"\n";
    }
}