简体   繁体   English

如何从XML文档中提取数据

[英]how to extract data from a XML doc

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

gives: 得到:

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

how do I use a foreach loop to extract 'id' and other info. 如何使用foreach循环提取“ id”和其他信息。

To access data you need to know about xml structure. 要访问数据,您需要了解xml结构。 As I see from dump you can access all first list node's attributes like this: 从转储中可以看到,您可以像这样访问所有第一个列表节点的属性:

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

For all nodes example: 对于所有节点的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM