Addition to my first note:
An traditional for-loop does not allow you to change the DOM-tree while looping - the effects are the nearly the same as with foreach. So you have to collect the nodes in an array and do the tree-altering stuff within a second loop (looping the array this time ...)
The DOMNodeList class
Class synopsis
DOMNodeList
class DOMNodeList
{
/* Properties */
/* Methods */
}Properties
- length
-
The number of nodes in the list. The range of valid child node indices is 0 to length - 1 inclusive.
Table of Contents
- DOMNodelist::item — Retrieves a node specified by index
DOMNodeList
drichter at muvicom dot de
14-May-2008 06:11
14-May-2008 06:11
drichter at muvicom dot de
14-May-2008 04:56
14-May-2008 04:56
I have done some testing and have found 2 results:
(My System: Win XP with PHP 5.2.1)
1) Iteration with foreach does function correctly as "james dot j dot hackett at gmail dot com" writes, _if_ you only do readonly stuff with foreach or minor writings of some attributes.
2) foreach does not function, if you are doing some DOM-Operations while iterating. In my situation it was adding the iterated $node as an child to an new node:
$newNode = $dom->createElement('newNode') ;
foreach ($nodeList as $node) {
echo $node->nodeValue ;
$newNode->appendChild($node) ;
}
This only gives you the first element ...
I'm interpreting it as an confusing but correct behavior because of the changes within the $dom-object while appending the node at an additional place ...
So, if you want to do something like 2) use for, length and item() :)
james dot j dot hackett at gmail dot com
08-May-2008 09:47
08-May-2008 09:47
In Response to 'kassah at gmail'
You don't need to convert a DOMNodeList to an array in order iterate through it using 'foreach'. You can use foreach directly with the DOMNodeList.
$nodeList = $someDomDocument->getElementsbytagname('user');
foreach ($nodeList as $node) {
echo $node->nodeValue;
}
kassah at gmail dot com
04-May-2008 05:06
04-May-2008 05:06
// Converts a DOMNodeList to an Array that can be easily foreached
function dnl2array($domnodelist) {
$return = array();
for ($i = 0; $i < $domnodelist->length; ++$i) {
$return[] = $domnodelist->item($i);
}
return $return;
}
brack at wjp dot de
21-Apr-2008 02:35
21-Apr-2008 02:35
In PHP 5.2.5 (Windows) it is not possible to iterate correctly over the DOMNodeList object returned by DOMNode->childNodes using foreach. Instead I had to use the for loop in conjunction with the item() method of DOMNodeList for iterating over all child nodes correctly.
I don't know whether this is really a bug, but apparently it is.
