美化存储在PHP字符串中的HTML [英] Beautify HTML stored in a string on PHP
问题描述
我在变量$html
中有一个字符串,其中包含最小化的HTMl代码,都在一行中,例如:
I have a string in variable $html
that contains minified HTMl code, all in one line, like:
$html = '<body><div><p>hello</p><div></body>';
如何美化/漂亮地打印HTML,以使我的变量变为:
How do I beautify/pretty print the HTML so that my variable becomes like:
$html = '<body>
<div>
<p>hello</p>
<div>
</body>';
我知道整洁扩展名是可行的,但是怎么可能无需扩展即可完成.
I know the tidy extension is a possibility, but how can this be done without an extension.
请阅读问题.我不是在问如何通过某些外部网站美化HTML代码.我在问如何在PHP中做到这一点,特别是针对字符串变量.
推荐答案
我们使用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>
这篇关于美化存储在PHP字符串中的HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!