Wazan
Wazan

Reputation: 539

How to get PHP DOM getElementsByTagName('body') with html tags

Im getting the body content but without html tags(It is cleaned up) inside the body.I need with all html tags inside the body. what do I want to change on my code?

$doc = new DOMDocument();
@$doc->loadHTMLFile($myURL);

$elements2 = $doc->getElementsByTagName('body');

        foreach ($elements2 as $el2) {
            echo $el2->nodeValue, PHP_EOL;
        echo "<br/>";
}   

Upvotes: 2

Views: 2995

Answers (1)

ThW
ThW

Reputation: 19492

You will need to save the body child nodes as HTML. I suggest using Xpath to fetch the nodes, this avoids the outer loop:

$html = <<<'HTML'
<html>
  <body>
    Foo
    <p>Bar</p>
  </body>
</html>
HTML;

$document = new DOMDocument();
$document->loadHtml($html);
$xpath = new DOMXpath($document);

$result = '';
foreach ($xpath->evaluate('//body/node()') as $node) {
  $result .= $document->saveHtml($node);
}
var_dump($result);

Output:

string(29) "
    Foo
    <p>Bar</p>
  "

Upvotes: 1

Related Questions