递归迭代SimpleXML对象*,其中结构未知*

问题描述 投票:0回答:1

我在网上找到的xml迭代的每个例子(包括PHP文档,W3Schools和stackoverflow搜索)都假设我们提前知道结构。我想创建一个循环,迭代尽可能深入每个分支,并简单地返回它找到的节点名称和值。例如:

<za-lord>
    <orderid>dresden1234</orderid>
    <customer>toot-toot</customer>
    <pizza>
        <sauce>marinara</sauce>
        <crust>thin</crust>
        <toppings>
            <cheese>extra</cheese>
            <veg>
                <onions>yes</onions>
                <peppers>extra</peppers>
                <olives>no</olives>
            </veg>
            <meat>
                <groundbeef>yes</groundbeef>
                <ham>no</ham>
                <sausage>no</sausage>
            </meat>
        </toppings>
    </pizza>
</za-lord>  

那么我正在寻找的是:

orderid = dresden1234
customer = toot-toot
sauce = marinara
crust = thin
cheese = extra
onions = yes
peppers = extra
olives = no
groundbeef = yes
ham = no
sausage = no 

我花了几个小时现在编写代码示例,测试foreach上的不同变体,简短的版本是没有任何东西让我得到我想要的东西。提前不知道结构,是否可以递归迭代上面的xml并使用SimpleXML返回节点名称和值,如果是,如何?

php xml simplexml
1个回答
0
投票

您可以使用SimpleXMLIterator对象并对其进行递归以获取所有节点值:

function list_nodes($sxi) {
    for($sxi->rewind(); $sxi->valid(); $sxi->next() ) {
        if ($sxi->hasChildren()) {
            list_nodes($sxi->current());
        }
        else {
            echo $sxi->key() . " = " . $sxi->current() . "\n";
        }
    }
}
$sxi = new SimpleXMLIterator($xmlstr);
list_nodes($sxi);

输出:

orderid = dresden1234 
customer = toot-toot 
sauce = marinara 
crust = thin 
cheese = extra 
onions = yes 
peppers = extra 
olives = no 
groundbeef = yes 
ham = no 
sausage = no

Demo on 3v4l.org

更新

如果您的xml可以具有名称空间,则必须采用更复杂的方法,检查文档中每个名称空间中的子节点的每个节点:

function list_children($node, $names) {
    $children = false;
    foreach ($names as $name) {
        if (count($node->children($name))) {
            $children = true;
            foreach ($node->children($name) as $child) {
                list_children($child, $names);
            }
        }
    }
    if (!$children) {
        echo $node->getName() . " = $node\n";
    }
}

$xml = new SimpleXMLElement($xmlstr);
list_children($xml, array_merge(array(''), $xml->getNamespaces(true)));

输出(对于demo xml,与问题相同,但添加了名称空间):

orderid = dresden1234 
customer = toot-toot 
sauce = marinara 
crust = thin 
cheese = extra 
onions = yes 
peppers = extra 
olives = no 
ham = no 
sausage = no
groundbeef = yes 

Demo on 3v4l.org

© www.soinside.com 2019 - 2024. All rights reserved.