iltdev
iltdev

Reputation: 1835

PHP - xPath DOM element to HTML string

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?

Upvotes: 1

Views: 2634

Answers (1)

Kevin
Kevin

Reputation: 41893

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);

Upvotes: 1

Related Questions