Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add elements to DOMNodeList in PHP?

Is there a way to create my own DOMNodeList? E.g.:

$doc = new DOMDocument(); 
$elem = $doc->createElement('div');
$nodeList = new DOMNodeList; 
$nodeList->addItem($elem); // ?

My idea is to extend DOMDocument class adding some useful methods that return data as DOMNodeList.

Is it possible to do it without writing my own version of DOMNodeList class?

like image 582
optimizitor Avatar asked Nov 29 '14 08:11

optimizitor


1 Answers

You cannot add items to DOMNodeList via it's public interface. However, DOMNodeLists are live collections when connected to a DOM Tree, so adding a Child Element to a DOMElement will add an element in that element's child collection (which is a DOMNodeList):

$doc = new DOMDocument();
$nodelist = $doc->childNodes; // a DOMNodeList
echo $nodelist->length;       // 0

$elem = $doc->createElement('div');
$doc->appendChild($elem);

echo $nodelist->length;       // 1

You say you want to add "some useful methods that return data as DOMNodeList". In the context of DOMDocument, this is what XPath does. It allows you to query all the nodes in the document and return them in a DOMNodeList. Maybe that's what you are looking for.

like image 51
Gordon Avatar answered Nov 06 '22 05:11

Gordon