且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

美化存储在PHP字符串中的HTML

更新时间:2023-02-23 10:49:16

我们使用DomDocument加载通过LIBXML_HTML_NOIMPLIED标志传递的html
这将阻止loadHTML方法添加额外的html包装器.

Using DomDocument we load the html passing the LIBXML_HTML_NOIMPLIED flag
which will prevent the loadHTML method to add the extra html wrapper.

我们将另存为XML,以获得漂亮的缩进,同时传递$dom->documentElement参数以防止XML标头.

We save as XML to get the nice indentation, while passing the $dom->documentElement parameter to prevent the XML header.

$html = '<body><div><p>hello</p><div></body>';

$dom = new DOMDocument();

$dom->preserveWhiteSpace = false;
$dom->loadHTML($html,LIBXML_HTML_NOIMPLIED);
$dom->formatOutput = true;


print $dom->saveXML($dom->documentElement);

这将输出

<body>
  <div>
    <p>hello</p>
    <div/>
  </div>
</body>

请注意,HTML已为您修复,因为我想第二个div应该是结束标记.

Notice that the HTML was fixed for you as the second div should have been a closing tag, I assume.

如果我们将正确的HTML作为输入字符串传递,则输出将根据您的要求

If we pass the proper HTML as the input string, the output will be as you require

$html = '<body><div><p>hello</p></div></body>';

<body>
  <div>
    <p>hello</p>
  </div>
</body>