XML获取具有子节点的节点

时间:2018-01-12 22:34:45

标签: php xml

我有以下XML结构:

enter image description here

正如您所看到的,我有许多节点名为" Activity" 现在我想知道,我怎样才能得到所有"活动"节点及其子节点?

我需要一个php解决方案,我尝试过类似的东西:

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

但这不起作用。 有任何想法吗? 谢谢:))

1 个答案:

答案 0 :(得分:0)

请勿使用children(),而只是遍历Activities

例如:

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