【问题标题】:Preventing DOMDocument from stripping white spaces after empty tags防止 DOMDocument 在空标签后去除空格
【发布时间】:2012-10-28 23:21:38
【问题描述】:

我有一个通过 DOMDocument 加载的 html 文件,我在其中做一些 DOM 操作,输出带有 saveHTML 的 html。

问题是输入标签后面的空格被去掉了,这里是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();

它在我尝试过的其他标签(&lt;br&gt;&lt;hr&gt;)之后删除了空格,&lt;head&gt; 中的标签除外。

我尝试将formatOutput 设置为true,但这只保留了结束标记前的空格。

有没有办法让 DOMDocument 在我的&lt;input&gt;s 之后保留空格?

【问题讨论】:

  • 将空格转换为&amp;nbsp;&amp;#160;。不间断的空间不会折叠。
  • @JeremyJStarcher 它没有折叠并被移除,我也在寻找不涉及更改标记的解决方案。

标签: php html domdocument


【解决方案1】:

我知道这是一个老问题,当我遇到这个https://bugs.php.net/bug.php?id=50278时,我正在寻找同样的东西

在注释中它说通过LIBXML_HTML_NODEFDTD 作为这样的选项:

$doc = new DOMDocument();

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

echo $doc->saveHTML();

这将保留空白。

【讨论】:

  • 感谢您的回复,但我无法让它工作。我有PHP Version 5.4.15libxml2 Version 2.7.8。你让它工作了吗?
  • 我想我有 5.6.x 和它附带的任何东西,它对我有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 2013-04-17
相关资源
最近更新 更多