I am trying to get a child of a PHP DOMDocument. Say I have a DOM document like this:
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.