SimpleXML 有它自己的 SPL 迭代器。參考 https://php.dev.org.tw/~helly/php/ext/spl/classSimpleXMLIterator.html。但我猜 DOM 節點沒有。順便一提,我在網路上找到的三個實作範例中有兩個不是遞迴的,所以我寫了自己的。以下是程式碼片段:
<?php
class DOMNodeListIterator implements RecursiveIterator
{
private
$nodes,
$offset;
function __construct(DOMNodeList $nodes)
{
$this->nodes = $nodes;
return $this;
}
function rewind()
{
$this->offset = 0;
return;
}
function current()
{
return $this->nodes->item($this->offset);
}
function key()
{
return $this->current()->nodeName;
}
function next()
{
$this->offset++;
return;
}
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);
?>
應該可以運作,雖然只測試了幾分鐘。 :)