SimpleXML 有自己的 SPL 迭代器。查看 https://php.net/~helly/php/ext/spl/classSimpleXMLIterator.html 。但我认为 DOM 节点没有。顺便说一句,我发现的三个实现中有两个不是递归的,所以我写了自己的。以下是代码片段
<?php
class DOMNodeListIterator implements RecursiveIterator
{
private
$nodes,
$offset;
function __construct(DOMNodeList $nodes)
{
return $this -> nodes = $nodes;
}
function rewind()
{
return $this -> offset = 0;
}
function current()
{
return $this -> nodes -> item($this -> offset);
}
function key()
{
return $this -> current() -> nodeName;
}
function next()
{
return $this -> offset++;
}
function valid()
{
return $this -> offset < $this -> nodes -> length;
}
function hasChildren()
{
return isset($this -> current() -> childNodes -> length) && $this -> current() -> childNodes -> length > 0;
}
function getChildren()
{
return new self($this -> current() -> childNodes);
}
}
?>
记住,在创建迭代器迭代器时使用 RecursiveIteratorIterator::SELF_FIRST 标志。
<?php
$iterator = new DOMNodeListIterator($document -> childNodes);
$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
?>
应该可以工作,不过也就几分钟时间。:)