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:


/* 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(2).'<title>This is a title</title>'
    .nl(2).'<div id="some_container">';
if ($show_table)
    echo nl(3).'<table>'
        .nl(5).'<td>This is a cell in a table</td>'
echo nl(2).'</div><!--some_container-->'
    .nl(2).'<p>This is some text in a paragraph</p>'


The output will look like this:

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

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.


No comments yet.

Leave a comment