Extract and dump a DOM node (and its children) in PHP

’I have the following scenario and I’m already spending hours trying to handle it: I’m developing a WordPress theme (hence PHP) and I want to check whether the content of a post (which is HTML) contains a tag with a certain id/class. If so, I want to extract it from the content and place it somewhere else.
Example: Let’s say the text content of the WordPress post is

<?php
  /* $content actually comes from WP function get_the_content() */
  $content = '<p>some text and so forth that I don't care about...</p> <div class="the-wanted-element"><p>I WANT THIS DIV!!!</p></div>';
?>

So how can I extract that div with the class (could also live with giving it an ID), output it (with tags and all that) in one place of the template, and output the rest (without the extracted tag, of course) in another place of the template?
I’ve already tried with the DOMDocument class, p.i.t.a. to me, maybe I’m too stupid.

Related posts

Leave a Reply

1 comment

  1. Try:

    $content = '<p>some text and so forth that I don't care about...</p> <div class="the-wanted-element"><p>I WANT THIS DIV!!!</p></div>';
    
    $dom = new DomDocument;
    $dom->loadHtml($content);
    
    $xpath = new DomXpath($dom);
    $contents = '';
    foreach ($xpath->query('//div[@class="the-wanted-element"]') as $node) {
      $contents = $dom->saveXml($node);
      break;
    }
    
    echo $contents;
    

    How to get the remaining xml/html:

    $content = '<p>some text and so forth that I don't care about...</p> <div class="the-wanted-element"><p>I WANT THIS DIV!!!</p></div>';
    
    $dom = new DomDocument;
    $dom->loadHtml($content);
    
    $xpath = new DomXpath($dom);
    foreach ($xpath->query('//div[@class="the-wanted-element"]') as $node) {
      $node->parentNode->removeChild($node);
      break;
    }
    
    $contents = '';
    foreach ($xpath->query('//body/*') as $node) {
        $contents .= $dom->saveXml($node);
    }
    
    echo $contents;