How to output formatted HTML from PHP?

14,459

Solution 1

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.

Solution 2

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>
Share:
14,459
Tim
Author by

Tim

Updated on June 05, 2022

Comments

  • Tim
    Tim almost 2 years

    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 from 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?