简体   繁体   English

如何从PHP输出格式化的HTML?

[英]How to output formatted HTML from PHP?

I like to format all my HTML with tabs for neatness and readability. 我喜欢使用标签格式化我的所有HTML,以获得整洁和可读性。 Recently I started using PHP and now I have a lot of HTML output that comes from in between PHP tags. 最近我开始使用PHP,现在我有很多来自PHP标签之间的HTML输出。 Those output lines all line up one the left side of the screen. 这些输出线都排在屏幕左侧的一侧。 I have to use /n to make a line go to the next. 我必须使用/n来制作一行到下一行。 Is there anything like that for forcing tabs, or any way to have neat HTML output coming from PHP? 有什么类似的强制标签,或任何方式来从PHP得到整洁的HTML输出?

If there is relative bigger blocks of html you are outputting then HEREDOC syntax would help you format the html the way you want witout bothering much about echo tabs using php. 如果你输出的是相对较大的html块,那么HEREDOC语法将帮助你以你想要的方式格式化html,而不用使用php来打扰echo选项卡。

$html = <<<HTML
<html>
  <head><title>...</title></head>
  <body>
     <div>$phpVariable</div>
  </body>
</html>
HTML;

If you use some tool to parse your html , remember it will also add an extra overhead of processing and data payload for each request so you might want to do it only for debug purposes. 如果您使用某种工具来解析您的html,请记住它还会为每个请求添加额外的处理和数据有效负载开销,因此您可能只想进行调试。

There's the tidy extension which helps you to (re-)format your html output. 有一个整洁的扩展 ,可以帮助您(重新)格式化您的HTML输出。
But it has a little price tag attached to it. 但它附有一点价格标签。 Parsing the output and building an html dom isn't exactly cost free. 解析输出并构建html dom并不是完全免费的。

edit: Could also be that you're simply looking for the \\t "character". 编辑:也可能是你只是在寻找\\t “字符”。 Eg 例如

<html>
  <head><title>...</title></head>
  <body>
<?php
  for($i=0; $i<10; $i++) {
    echo "\t\t<div>$i;</div>\n";
  }
?>
  </body>
</html>

or you nest and indent your php/html code in a way that the output is indented nicely. 或者你以一种很好地缩进输出的方式嵌套和缩进你的php / html代码。 (Sorry for the ugly example:) (抱歉这个丑陋的例子:)

<html>
  <head><title>...</title></head>
  <body>
<?php for($i=0; $i<10; $i++) { ?>
    <div><?php echo $i; ?></div>
<?php } ?>
  </body>
</html>
<html>
    <head><title>...</title></head>
    <body>
<?php for($i=0; $i<10; $i++) { ?>
    <div><?php echo $i; ?></div>
<?php } ?>
</body>
</html>

Actually this is a good example but in this case it's better to use Alternative way of doing things 实际上这是一个很好的例子,但在这种情况下,最好使用Alternative方式做事

<html>
    <head><title>...</title></head>
    <body>
<?php for($i=0; $i<10; $i++): ?> // notice the colon
    <div><?php echo $i; ?></div>
<?php endfor; ?>
</body>
</html>

Reference 参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM