DOMNode to DOMElement in php

后端 未结 5 1478
南旧
南旧 2021-02-13 20:15

I want to convert a DOMNode object from a call to getElementsByTagName() to a DOMElement in order to access methods like getElements

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 21:07

    You don't need to cast anything, just call the method:

    $links = $dom->getElementsByTagName('a');
    
    foreach ($links as $link) {
        $spans = $link->getElementsByTagName('span');
    }
    

    And by the way, DOMElement is a subclass of DOMNode. If you were talking about a DOMNodeList, then accessing the elements in such a list can be done, be either the method presented above, with a foreach() loop, either by using the item() method of DOMNodeList:

    $link_0 = $dom->getElementsByTagName('a')->item(0);
    

提交回复
热议问题