DomDocument removeChild in foreach reindexing the dom

前端 未结 4 1333
梦毁少年i
梦毁少年i 2021-01-18 11:25

I am trying to delete p tags with data-spotid attribute

        $dom = new DOMDocument();
        @$dom->loadHTML($description);         


        
4条回答
  •  有刺的猬
    2021-01-18 11:55

    Like I commented, the easy solution would be to just cast the iterator to an array. E.g.:

    $elements = iterator_to_array($elements);
    

    But, if we're talking about performance, a better way would be to simply select only the required nodes. Neat side-effect, the removal-problem also goes away.

    E.g.:

    loadXML(<<<__XML
    
    
        1
        2
        3
        4
        5
        6
        7
        8
    
    __XML
    );
    
    $xpath = new DOMXPath($doc);
    $elements = $xpath->query('//element[@attr]');
    
    foreach ($elements as $element) {
        $element->parentNode->removeChild($element);
    }
    
    echo $doc->saveXML();
    

    Demo: https://3v4l.org/CM9Fv

提交回复
热议问题