Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 31st, 2012  |  syntax: None  |  size: 1.09 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Extract and dump a DOM node (and its children) in PHP
  2. <?php
  3.   /* $content actually comes from WP function get_the_content() */
  4.   $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>';
  5. ?>
  6.        
  7. $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>';
  8.  
  9. $dom = new DomDocument;
  10. $dom->loadHtml($content);
  11.  
  12. $xpath = new DomXpath($dom);
  13. $contents = '';
  14. foreach ($xpath->query('//div[@class="the-wanted-element"]') as $node) {
  15.   $contents = $dom->saveXml($node);
  16.   break;
  17. }
  18.  
  19. echo $contents;
  20.        
  21. $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>';
  22.  
  23. $dom = new DomDocument;
  24. $dom->loadHtml($content);
  25.  
  26. $xpath = new DomXpath($dom);
  27. foreach ($xpath->query('//div[@class="the-wanted-element"]') as $node) {
  28.   $node->parentNode->removeChild($node);
  29.   break;
  30. }
  31.  
  32. $contents = '';
  33. foreach ($xpath->query('//body/*') as $node) {
  34.     $contents .= $dom->saveXml($node);
  35. }
  36.  
  37. echo $contents;