1

I'm using PHP's DOMDocument to remove divs matching a specific class name. So in my example below, I'm removing any element with the class name of 'remove-me'.

  $content = '<div class="keep-me">Keep this div</div><div class="remove-me">Remove this div</div>';

         $badClasses = array('remove-me');

         libxml_use_internal_errors(true);
         $dom = new DOMDocument();
         $dom->loadHTML($content);

         $xPath = new DOMXpath($dom);

         foreach($badClasses as $badClass){
            $domNodeList =  $nodes = $xPath->query('//*[contains(@class, "'.$badClass.'")]');
            $domElemsToRemove = array();
            foreach ( $domNodeList as $domElement ) {
              // ...do stuff with $domElement...
              $domElemsToRemove[] = $domElement;
            }
            foreach( $domElemsToRemove as $domElement ){
              $domElement->parentNode->removeChild($domElement);
            } 
         }

         $content = $dom->saveHTML();

Is there any way I can keep all the removed element, convert them to a HTML string so that I can echo the html elsewhere on my page?

1 Answer 1

1

Yes you still can get to keep those removed markup. Before deleting, put them inside a string container first. You don't actually need two foreach loops. One is sufficient:

$content = '<div class="keep-me">Keep this div</div><div class="remove-me">Remove this div</div>';
$badClasses = array('remove-me');

$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($content);
libxml_clear_errors();
$xPath = new DOMXpath($dom);

foreach($badClasses as $badClass){
    $domNodeList = $xPath->query('//*[contains(@class, "'.$badClass.'")]');

    $domElemsToRemove = ''; // container of deleted elements
    foreach ( $domNodeList as $domElement ) {
        $domElemsToRemove .= $dom->saveHTML($domElement); // concat them
        $domElement->parentNode->removeChild($domElement); // then remove
    }

}

$content = $dom->saveHTML();
echo 'html removed <br/>';
echo htmlentities($domElemsToRemove);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.