PHP DOM: How to get child elements by tag name in an elegant manner?

后端 未结 3 1566
有刺的猬
有刺的猬 2020-12-04 01:53

I\'m parsing some XML with PHP DOM extension in order to store the data in some other form. Quite unsurprisingly, when I parse an element I pretty often need to obtain all c

3条回答
  •  盖世英雄少女心
    2020-12-04 02:27

    An elegant manner I can imagine would be using a FilterIterator that is suitable for the job. Exemplary one that is able to work on such a said DOMNodeList and (optionally) accepting a tagname to filter for as an exemplary DOMElementFilter from the Iterator Garden does:

    $a = $doc->getElementsByTagName('a')->item(0);
    
    $bs = new DOMElementFilter($a->childNodes, 'b');
    
    foreach($bs as $b){
        echo $b->nodeValue . "\n";
    }
    

    This will give the results you're looking for:

    1
    2
    

    You can find DOMElementFilter in the Development branch now. It's perhaps worth to allow * for any tagname as it's possible with getElementsByTagName("*") as well. But that's just some commentary.

    Hier is a working usage example online: https://eval.in/57170

提交回复
热议问题