PHP: a DOMNodeList is not an array

Most developers who start using the PHP's DOM extension sometimes get confused by the concept of DOMNodeList. In the DOM terminology, a node list is an ordered collection of nodes which has a length and an item property. The former returns the number of elements contained within the node list, while the latter accepts an integer as its value (starting from 0) by which you can access a given node within that list. The DOM specifications (created by the W3C) state that a node list is actually an interface, not an array. PHP implements this component as a class (object), not as an array (thus following the DOM specifications).

This means that you cannot use array functions on a node list, because you're dealing with an object, not with an array. For example, given the following XML document:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <item>1</item>
  <item>2</item>
  <item>3</item>
</root>

you can do the following tests:

$xml = new DOMDocument();
$xml->load('test.xml');
$items = $xml->getElementsByTagName('item');


var_dump($items); //object(DOMNodeList)#2 (0) { }

$item = $items->item(0);

var_dump($item); //object(DOMElement)#3 (0) { }

Each member of a DOMNodeList is a DOMElement, which means that we're dealing with objects again. If you want to use array functions on the values of each element, you have to convert such values into an array first:

$arr = array();

foreach($items as $element) {


  $arr[] = $element->firstChild->nodeValue;


}


var_dump($arr); 
// array(3) { [0]=> string(1) "1" [1]=> string(1) "2" [2]=> string(1) "3" }

Done that, you can use normal array functions on such an array:

var_dump(array_reverse($arr)); 
// array(3) { [0]=> string(1) "3" [1]=> string(1) "2" [2]=>string(1) "1" }

Leave a Reply

Note: Only a member of this blog may post a comment.