You are here

22 September 2016

How to use a DOM parser and get the contents of the body.

Source code viewer
  1. <?php
  2.  
  3. // HTML to Dom Document.
  4. $doc = new DOMDocument();
  5. $doc->strictErrorChecking = false;
  6. $doc->loadHTML('<?xml encoding="UTF-8" ?>' . $content);
  7.  
  8. // Get body tag.
  9. $body = $doc->getElementsByTagName('body');
  10. if ($body and $body->length > 0) {
  11. $body = $body->item(0);
  12.  
  13. // Do stuff with the body tag...
  14.  
  15. // Get altered HTML and clean up.
  16. $html = $doc->saveHTML();
  17. $html = str_replace('<?xml encoding="UTF-8" ?>', '', $html);
  18.  
  19. // Return modified HTML.
  20. echo $html;
  21. }
Programming Language: PHP