PHP DOMDocument: Delete elements by class

前端 未结 3 574
盖世英雄少女心
盖世英雄少女心 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:46

    For the second part of the question, the result of the query has a length property which you can use to see if anything was matched:

    $xpath = new DOMXPath($doc);
    $nodes = $xpath->query('//div[contains(attribute::class, "foo")]');
    
    printf('Removing %d nodes', $nodes->length);
    
    0 讨论(0)
  • 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 = <<<EOF
    <div class="main">
        <div class="delete_this" contenteditable="true">Target</div>
        <div class="class1"></div>
        <div class="content"><p>Anything</p></div>
    </div>
    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);
    
    0 讨论(0)
  • 2021-01-15 04:57

    This removes all divs with that class. To actually remove all the elements by class use *:

    $selector = new \DOMXPath( $doc );
    foreach ( $selector->query( '//*[contains(attribute::class, "' . $class . '")]' ) as $e ) {
      $e->parentNode->removeChild( $e );
    }
    
    0 讨论(0)
提交回复
热议问题