clearscrn clearscrn - 1 month ago 22
HTML Question

Php extract html body content along with html tags not only plain text

I am new in php. I am trying to extract entire body tag from html using php.

Here the my sample html:

<html>
<body >
<p>
Example html content
</p>
</body>
</html>


I want extract only following contentfrom html content:

<p>
Example html content
</p>


Using following I tried solve but it's output only string without html tags:

$dom = new domDocument;
$dom->loadHTML("<html><body><p>Example html content</p></body></html>");
$body = $dom->getElementsByTagName('body')->item(0);
var_dump($body->textContent); //output:Example html content


Please help me to resolve this issue.

Answer

Update your code as following:

   $dom = new domDocument;
   $dom->loadHTML("<html><body><p>Example html content</p></body></html>");
   $body = $dom->getElementsByTagName('body')->item(0);
   var_dump($dom->savehtml($body));

Output should be along with html tags:

string(26) "<p>Hello!</p>"