Tabbed include in PHP

This is a really old entry — I will no longer vouch for its sanity. :)

Ever found it hard to read HTML sources without proper indentation? Ever tried to use proper indentation on your own sites, but given up because PHP and dynamic content messed up your brave attempt? Here’s something I whipped up for the SmestadLAN site, tabbed include:

<?php

function tabulatorInclude($file, $tabwidth)
{
  ob_start();
  include($file);
  $output = ob_get_clean();
  $lines = explode("\n", $output);
  $whitespace = "";
  for ($i = 0; $i < $tabwidth; $i++)
    $whitespace = $whitespace." ";
  foreach ($lines as $line)
  {
    echo $whitespace.$line."\n";
  }
}

?>

What this effectively does, is:

  • Turn on output buffering
  • Include the file specified in $file
  • Retreive the buffer and turn it off
  • Pad each line with the number of whitespaces specified in $tabwidth

Though probably not the best written lines of PHP code, it does its job.

Posted in Guides, PHP

Comments