简体   繁体   中英

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.

To access data you need to know about xml structure. 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";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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