美化存储在PHP字符串中的HTML [英] Beautify HTML stored in a string on PHP

查看:73
本文介绍了美化存储在PHP字符串中的HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在变量$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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆