开发者

How to get a child of PHP DOMDocument by index

开发者 https://www.devze.com 2023-03-06 21:32 出处:网络
开发者_C百科I am trying to get a child of a PHP DOMDocument. Say I have a DOM document like this:
开发者_C百科

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?


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.


If you use DOMDocument you can use getElementsByTagName('*') which returns a DomNodeList with all elements in your document. You can then invoke the item function which takes an index as a parameter:

$nodes = $dom->getElementsByTagName('*');
$targetNode = $nodes->item(3);


try this

 foreach($dom->getElementsByTagName('div') as $div) { 
        $class = $div->getAttribute('class');
    } 

now you can match the class or id attribute of that particular div and do what ever. this is not the solution but helps you find the contents and attributes with all divs' . hope it helps.


Try this:

$dom->childNodes->item(3)
0

精彩评论

暂无评论...
验证码 换一张
取 消