Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output formatted HTML from PHP?

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?

like image 255
Tim Avatar asked Sep 13 '25 00:09

Tim


2 Answers

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.

like image 81
jayadev Avatar answered Sep 15 '25 13:09

jayadev


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>
like image 29
VolkerK Avatar answered Sep 15 '25 13:09

VolkerK