简体   繁体   中英

XML get nodes with sub nodes

I have the following XML structure:

在此处输入图片说明

As you can see, I have many nodes with the name "Activity" Now I would like to know, how can I get all "Activity" nodes with their sub nodes?

I need a php solution and I tried something like that:

foreach($xml->Shipment->Package->children() as $activites) { 
    echo $activites->Status->StatusType->Description;
} 

But this doesn't work. Any ideas? Thank you :)

Don't use children() , instead just iterate over the Activities .

For example:

<?php
$xml = '<?xml version="1.0" encoding="utf-8"?>
<TrackResponse>
    <Shipment>
        <Package>
            <Activity>
                <Status>
                    <StatusType>
                        <Description>Foo</Description>
                    </StatusType>
                </Status>
            </Activity>
            <Activity>
                <Status>
                    <StatusType>
                        <Description>Bar</Description>
                    </StatusType>
                </Status>
            </Activity>
            <Activity>
                <Status>
                    <StatusType>
                        <Description>Baz</Description>
                    </StatusType>
                </Status>
            </Activity>
        </Package>
    </Shipment>
</TrackResponse>';

$xml = simplexml_load_string($xml);

foreach ($xml->Shipment->Package->Activity as $activites) {
    echo $activites->Status->StatusType->Description.PHP_EOL;
}

https://3v4l.org/BJDZC

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