How to prevent DOMDocument from wrapping result in <p> tags?

Viewed 90

There's a million hits for this subject and none of them seem to have worked for me. So I have to ask it again. Say, if I have this:

$html = "&quot;PHP&quot; is documented <a href=\"https://php.net\">here</a>.";

$dom = new DOMDocument();
$dom->strictErrorChecking = false;
$dom->preserveWhiteSpace = true;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$newHtml = $dom->saveHTML();

echo(htmlentities($newHtml));

Why as an output I'm getting:

<p>"PHP" is documented <a href="https://php.net">here</a>.</p>

Where's this <p> coming from? Didn't I ask not to do it in LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD?

Anyway, does someone have a solution to this that works?

1 Answers

You can go around this problem by force wrapping your HTML content then unwrapping it by selecting its child, like that:

$html = "&quot;PHP&quot; is documented <a href=\"https://php.net\">here</a>.";

$dom = new DOMDocument();
$dom->loadHTML("<div>".$html."</div>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$inner_html = "";
foreach ($dom->documentElement->childNodes as $child) {
    $inner_html .= $dom->saveHTML($child);
}
echo $inner_html;

Output:

"PHP" is documented <a href="https://php.net">here</a>.
Related