Auto-indent HTML Code and Display It

喜你入骨 提交于 2019-12-12 09:10:32

问题


When displaying HTML code in PHP, if I want to indent tags what would be the best way?

For example,

<?php
$html = '<div><p><span>some text</span></p></div>';

echo htmlspecialchars($html);
?>

will give <div><p><span>some text</span</p></div>.

Instead, I'd like to show something like,

<div>
    <p>
        <span>some text</span>
    </p>
</div>

回答1:


You can use htmLawed
http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/

this would be your code:

<?php
  require("htmLawed/htmLawed.php");
  echo "<pre>";
  echo htmlspecialchars(
         htmLawed('<div><p><span>some text</span></p></div>', array('tidy'=>4))
       );
  echo "</pre>";
?>



回答2:


You may also want to use the HEREDOC.

 $html = <<<NICE

 <div>
     <p>
         <span>some text</span>
     </p>
 </div>

 NICE;

 echo "<pre>";
 echo htmlspecialchars( $html );
 echo "</pre>";



回答3:


You may need to know PHP Tidy extension.

Tidy is a binding for the Tidy HTML clean and repair utility which allows you to not only clean and otherwise manipulate HTML documents, but also traverse the document tree.




回答4:


If you know how you want it to be output (as in what your string will look like as you make it), you can easily do it like this:

$html = "<div>\n\t\t<p>\n\t\t\t<span>some text</span>\n\t\t</p>\n\t</div>";

Be sure to use double quotes though, not single ones.

Output as viewed in source code:

<div>
    <p>
        <span>some text</span>
    </p>
</div>

If you want to have it done automatically, then you might have to hold out for another answer, I don't really know much regex to help, and I don't use DOM (not even sure if it is applicable in this situation).



来源:https://stackoverflow.com/questions/12175190/auto-indent-html-code-and-display-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!