Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing DOMDocument from stripping white spaces after empty tags

I have an html file I load through DOMDocument in which I do some DOM manipulations the output the html with saveHTML.

The problem is that the white spaces after the input tags are removed, here is the HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title></title>
        <link rel="stylesheet" type="text/css" href="/style.css">
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script>
            window.jQuery || document.write(unescape('%3cscript src="/script/jquery.min.js"%3e%3c/script%3e'));
        </script>
    </head>
    <body>
        <div>
<div>
    <form method="post" action="/register/">
        <label>First name: <input type="text" name="firstname"></label>
        <label>Last name: <input type="text" name="lastname"></label>
        <label>Date of birth: <input type="date" name="dateofbirth"></label>
        <label>Address: <input type="text" name="address"></label>
        <label>Phone number: <input type="text" name="phonenumber"></label>
        <label>Sex: <input type="text" name="sex"></label>
        <label>Email address: <input type="email" name="email"></label>
        <label>Account password: <input type="password" name="password"></label>
        <input id="register-button" type="submit" value="Register">
        <input type="reset" value="Reset">
        <input type="button" value="Cancel">
    </form>
</div>
        </div>
    </body>
</html>

PHP

$template_file = $_SERVER['DOCUMENT_ROOT']."/application/template/template.html";
$doc = new DOMDocument('1.0', 'utf-8');
$doc->loadHTMLFile($template_file);
/* dom manipulation, importing and appending nodes from other documents etc */ 
echo $doc->saveHTML();

It striped the whitespaces after other tags I tried(<br>, <hr>) except tags in the <head>.

I tried setting formatOutput to true but that only kept the spaces before a closing tag.

Is there a way to make DOMDocument preserve the white spaces after my <input>s?

like image 772
Musa Avatar asked Oct 28 '12 23:10

Musa


1 Answers

I know this is an old issue, and I was looking for the same thing when I came across this https://bugs.php.net/bug.php?id=50278

In the notes it says to pass LIBXML_HTML_NODEFDTD as an option like this:

$doc = new DOMDocument();

$doc->loadHTMLFile($file, LIBXML_HTML_NODEFDTD);

echo $doc->saveHTML();

This will keep the white space.

like image 144
Get Off My Lawn Avatar answered Nov 18 '22 12:11

Get Off My Lawn