Hello
I'm making RSS reader and I'm using DOM.
Now I stuck, trying to reverse the order of the items in the DOMNodeList.
I can make it with 2 cycles - one to make it as array and one for rsort().
Is there any way to reverse the order in the DOMNodeList or must be done with "the array way"?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
There is no method for reversing a DOMNodeList.
But you can keep it as it is, and if you need it, walk through it from the end to the start.
Example:
<?php
$doc=new DOMDocument;
$doc->loadXML('
<div>
<span>1
<span>2
<span>3
</span>
</span>
</span>
</div>');
$nodeList=$doc->getElementsByTagName('span');
for($n=$nodeList->length-1;$n>=0;--$n)
{
echo $nodeList->item($n)->firstChild->data;//returns 321
}
?>
Just point at the end of the NodeList using NodeList->length, then decrement the index and access NodeList->item(index)
回答2:
An alternative to using a documentFragment (which can end up with an unwanted "default:" namespace prefix): clone the NodeList, transfer all the items to the clone, then replace the original node:
function reverseNodeList($nodeList) {
// clone the original node
$reverseNodeList = $nodeList->cloneNode();
// move all nodes off the bottom of the original list onto the new one
while ($nodeList->lastChild) $reverseNodeList->appendChild($nodeList->lastChild);
// replace the original node with the new one
$nodeList->parentNode->replaceChild($reverseNodeList, $nodeList);
}
回答3:
Why don't you do it on the client side using javascript? The code for a given node n would be:
function reverse(n) { // Reverses the order of the children of Node n
var f = document.createDocumentFragment( ); // Get an empty DocumentFragment
while(n.lastChild) // Loop backward through the children,
f.appendChild(n.lastChild); // moving each one to the DocumentFragment
n.appendChild(f); // Then move them back (in their new order)
}