Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a child of PHP DOMDocument by index

Tags:

dom

php

I am trying to get a child of a PHP DOMDocument. Say I have a DOM document like this:

<div>
   <h1 ></h1>
   <div id=2></div>
   <div class="test"></div>
...
</div>

I have a index number 3. Then I need to get the element <div class="test"></div>. In the DOMDocument API, there isn't a method like children(3). Is there? How can I get a child with an index?

like image 329
bingjie2680 Avatar asked May 18 '11 07:05

bingjie2680


2 Answers

Try this:

$dom->childNodes->item(3)
like image 183
Steven Vachon Avatar answered Sep 28 '22 06:09

Steven Vachon


You can use childNodes. This is a property of a DOM element that contains a NodeList containing all the element's children. Ideally you'd be able to do $el->childNodes->item(2) (note that it's 0-based, not 1-based, so 2 is the third item). However, this includes text nodes. So it's hard to predict what number your node will be. This probably isn't the best solution.

You could go with alexn's solution (getElementsByTagName('*')->item(2)), but again this has its drawbacks. If your nodes have child nodes, they will also be included in the selection. This could throw your calculation off.

My preferred solution would be to use XPath: it's probably the most stable solution, and not particularly hard.

You'll need to have created an XPath object with $xpath = new DOMXPath($document) somewhere, where $document is your DOMDocument instance. I'm going to assume that $el is the parent div node, the "context" that we're searching in.

$node = $x->query('*', $el)->item(2);

Note that, again, we're using a 0-based index to find which element in the selection it is. Here, we're looking at child nodes of the top level div only, and * selects only element nodes, so the calculations with text nodes are unnecessary.

like image 43
lonesomeday Avatar answered Sep 28 '22 08:09

lonesomeday