DomDocument removeChild in foreach reindexing the dom

前端 未结 4 1368
梦毁少年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:56

    This is mentioned in a couple of comments on the DomNode::removeChild documentation, with the issue apparently being how the iterator pointer on the foreach not being able to deal with the fact that you are removing items from a parent array while looping through the list of children (or something).

    The recommended fix is to loop through the main node first and push the child nodes you want to delete to its own array, then loop through that "to-be-deleted" array and deleting those children from their parent. Example:

    $dom = new DOMDocument();
    @$dom->loadHTML($description);
    $pTag = $dom->getElementsByTagName('p');
    
    $spotid_children = array();
    
    foreach ($pTag as $value) {
        /** @var DOMElement $value */
        $id = $value->getAttribute('data-spotid');
        if ($id) {
            $spotid_children[] = $value; 
        }
    }
    
    foreach ($spotid_children as $spotid_child) {
        $spotid_child->parentNode->removeChild($spotid_child); 
    }
    

提交回复
热议问题