我正在尝试使用PHP5.6.11版本中的SimpleXMLIterator按BFS顺序迭代一棵XML树。但是,我发现它只是遍历了嵌套在第一级的XML元素,在0级的根节点下面,跳过了级别2、3、.的所有嵌套元素。
那么,如何让迭代器遍历XML树BFS?
PHP文档提到迭代器应该是递归的。以下是代码:
<?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发布于 2015-08-24 16:09:09
使用以下方法:
$it = new RecursiveIteratorIterator(
new SimpleXmlIterator($xml),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($it as $key => $value){
print(trim($key) . PHP_EOL);
}http://ideone.com/5udHSg
发布于 2015-08-24 20:05:08
以下代码使用SimpleXMLIterator遍历XML树BFS样式,这是最初提出的问题。不幸的是,由于SimpleXMLIterator的设计方式,根元素似乎无法使用SimpleXMLElement输出。
<?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();
$currentSimpleXMLIterator = new SimpleXMLIterator($xmlCode);
$nonTraversedSimpleXMLIterators = array($currentSimpleXMLIterator);
while (count($nonTraversedSimpleXMLIterators) > 0) {
$currentSimpleXMLIterator = array_shift($nonTraversedSimpleXMLIterators);
for ($currentSimpleXMLIterator->rewind(); $currentSimpleXMLIterator->valid(); $currentSimpleXMLIterator->next()) {
if ($currentSimpleXMLIterator->hasChildren()) {
$childSimpleXMLIterator = $currentSimpleXMLIterator->getChildren();
array_push($nonTraversedSimpleXMLIterators, $childSimpleXMLIterator);
}
echo $currentSimpleXMLIterator->current()->getName(), "\n";
}
}
}
test();产出:
livingroom
bedroom
bathroom
kitchen
sofa
television
bed
sink
toilet
bath
fridge
leftPillow
rightPillow
sheet
duvet
pillow
bathtap
lettuce
snailhttps://stackoverflow.com/questions/32186565
复制相似问题