开发者

How to output formatted HTML from PHP?

开发者 https://www.devze.com 2022-12-25 00:38 出处:网络
I like to format all my HTML with tabs for neatness and readability. Recently I started using PHP and now I have a lot of HTML output that comes fr开发者_StackOverflowom in between PHP tags. Those out

I like to format all my HTML with tabs for neatness and readability. Recently I started using PHP and now I have a lot of HTML output that comes fr开发者_StackOverflowom in between PHP tags. 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. Is there anything like that for forcing tabs, or any way to have neat HTML output coming from PHP?


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 = <<<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.


There's the tidy extension which helps you to (re-)format your html output.
But it has a little price tag attached to it. Parsing the output and building an html dom isn't exactly cost free.

edit: Could also be that you're simply looking for the \t "character". E.g.

<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. (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

<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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号