22 September 2016

To use a DOMDocument and get the contents of the body in PHP, you can use the DOMDocument class, which provides a way to parse and manipulate XML and HTML documents. Here is an example of how to use DOMDocument to parse an HTML document and get the contents of the body tag.

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