Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PHP DOMDocument saveHTML($node) without added whitespace?

If I use saveHTML() without the optional DOMnode parameter it works as expected:

$html = '<html><body><div>123</div><div>456</div></body></html>';
$dom = new DOMDocument;
$dom->preserveWhiteSpace = true;
$dom->formatOutput = false;
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD);
echo $dom->saveHTML();
<html><body><div>123</div><div>456</div></body></html>

But when I add a DOMNode parameter to output a subset of the document it seems to ignore the formatOutput property and adds a bunch of unwanted whitespace:

$body = $dom->getElementsByTagName('body')->item(0);
echo $dom->saveHTML($body);
<body>
<div>123</div>
<div>456</div>
</body>

What gives? Is this a bug? Is there a workaround?

like image 795
Eaten by a Grue Avatar asked Nov 13 '18 19:11

Eaten by a Grue


2 Answers

Is this a bug?

Yes, it's a bug and it's reported here

Is there a workaround?

Stick with Nigel's solution for now

Did they fix it?

Yes, as of 7.3.0 alpha3 this is a fixed bug

Check it here

like image 182
Rain Avatar answered Sep 19 '22 00:09

Rain


If you know your document is going to be valid XML as well, you can use saveXML() instead...

$html = '<html><body><div>123</div><div>456</div></body></html>';
$dom = new DOMDocument;
$dom->preserveWhiteSpace = true;
$dom->formatOutput = false;
$dom->loadHTML($html, LIBXML_HTML_NODEFDTD);
$body = $dom->getElementsByTagName('body')->item(0);
echo $dom->saveXML($body);

which gives...

<body><div>123</div><div>456</div></body>
like image 45
Nigel Ren Avatar answered Sep 22 '22 00:09

Nigel Ren