Indenting HTML output in PHP

I care about indenting my HTML output from PHP scripts and prefer to keep this between the <?php ?> blocks. Another thing is that I want to keep my code < 80 chars/line. That’s why I use a very simple but neat function that helps me do this and read and check my HTML output more easily.

Below function safes you from using stuff like “/n/t/t” in your code. In this case you’d just use nl(2).
If you embrace the concept of using this simple function for your HTML output you can edit your code much easier and also much faster. This is especially true when using a modal editor like VI or Vim.

The code:

<?php

/* The 'nl' function */
function nl($tabs = 0) {
    $r = "\n";
    for ($i = 0; $i < $tabs; $i++)
        $r .= '   ';
    return $r;
}

/* Usage example */
$show_table = true;

echo '<!doctype html>';
echo nl().'<html>'
    .nl(1).'<head>'
    .nl(2).'<title>This is a title</title>'
    .nl(1).'</head>'
    .nl(1).'<body>'
    .nl(2).'<div id="some_container">';
if ($show_table)
    echo nl(3).'<table>'
        .nl(4).'<tr>'
        .nl(5).'<td>This is a cell in a table</td>'
        .nl(4).'</tr>'
        .nl(3).'</table>';
echo nl(2).'</div><!--some_container-->'
    .nl(2).'<p>This is some text in a paragraph</p>'
    .nl(1).'</body>'
    .nl().'</html>';

?>

The output will look like this:

<!doctype html>
<html>
   <head>
      <title>This is a title</title>
   </head>
   <body>
      <div id="some_container">
         <table>
            <tr>
               <td>This is a cell in a table</td>
            </tr>
         </table>
      </div><!--some_container-->
      <p>This is some text in a paragraph</p>
   </body>
</html>

This is of course very basic and I guess you can love or hate this style. 😉

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)