PHP DOMDocument: Delete elements by class

前端 未结 3 597
盖世英雄少女心
盖世英雄少女心 2021-01-15 04:24

I\' trying to delete every node with a given class.

To find the elements I use:

$xpath = new DOMXPath($dom);
    foreach( $xpath->query(\'//div[co         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-15 04:52

    You need to use the removeChild() method of the parent element:

    $xpath = new DOMXPath($dom);
    foreach($xpath->query('//div[contains(attribute::class, "foo")]') as $e ) {
        // Delete this node
        $e->parentNode->removeChild($e);
    }
    

    Btw, about your second question, if there are no elements found, the loop won't iterate at all.


    Here comes a working example:

    $html = <<
        
    Target

    Anything

    EOF; $doc = new DOMDocument(); $doc->loadHTML($html); $selector = new DOMXPath($doc); foreach($selector->query('//div[contains(attribute::class, "delete_this")]') as $e ) { $e->parentNode->removeChild($e); } echo $doc->saveHTML($doc->documentElement);

提交回复
热议问题