PHP中的SimpleXMLIterator不以BFS方式遍历XML树

时间:2015-08-24 15:52:09

标签: php xml tree iterator

我试图在php 5.6.7中使用SimpleXMLIterator以BFS顺序迭代XML树。但是,我发现它只是遍历嵌套在零级别根节点下一级的XML元素,跳过级别2,3,...的所有嵌套元素。

那么如何让迭代器以BFS方式遍历XML树呢?

PHP documentation提到迭代器应该是递归。这是代码:

<?php

function getXMLCode() {

  $xmlCode = <<<XML
  <home>
    <livingroom>
      <sofa>
        <leftPillow></leftPillow>
        <rightPillow></rightPillow>
      </sofa>
      <television></television>
    </livingroom>
    <bedroom>
      <bed>
        <sheet></sheet>
        <duvet></duvet>
        <pillow></pillow>
      </bed>
    </bedroom>
    <bathroom>
      <sink></sink>
      <toilet></toilet>
      <bath>
        <bathtap></bathtap>
      </bath>
    </bathroom>
    <kitchen>
      <fridge>
        <lettuce>
          <snail></snail>
        </lettuce>
      </fridge>
    </kitchen>
  </home>
XML;

  return $xmlCode;

}

function test() {

  $xmlCode = getXMLCode();

  $simpleXMLIterator = new SimpleXMLIterator($xmlCode);

  foreach ($simpleXMLIterator as $xmlElement) {

    echo $xmlElement->getName(), "\n";

  }

}

test();

这里是输出,如上所述,它不构成BFS遍历(加上根节点也被省略):

输出:

livingroom
bedroom
bathroom
kitchen

预期输出:

home
livingroom
bedroom
bathroom
kitchen
sofa
television
bed
sink
toilet
bath
fridge
leftPillow
rightPillow
sheet
duvet
pillow
bathtap
lettuce
snail

1 个答案:

答案 0 :(得分:1)

使用以下内容:

$it = new RecursiveIteratorIterator(
    new SimpleXmlIterator($xml),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach ($it as $key => $value){
    print(trim($key) . PHP_EOL);
}

http://ideone.com/5udHSg