Pretty Printing for PHP

This is a very old article. It has been imported from older blogging software, and the formatting, images, etc may have been lost. Some links may be broken. Some of the information may no longer be correct. Opinions expressed in this article may no longer be held.

Here’s a PHP function for reformatting the whitespace in PHP code:

$indentlevel = 0;
$output = ”;

foreach(token_get_all($sourcecode) as $token)
if (is_array($token))
list($tokentype, $spelling) = $token;
list($tokentype, $spelling) = array(NULL, $token);

if ($tokentype==T_WHITESPACE && preg_match(‘/\s$/’, $output))
elseif ($tokentype==T_WHITESPACE)
$spelling = ‘ ‘;

if ($spelling=='{‘)

if ($outmode==SC_IMPROVED_BRACES)
$output .= “\n$indent”;
elseif ($outmode==SC_WEIRDASS_BRACES)
$output .= “\n$indent\t”;
elseif ($spelling==’}’)
$output = preg_replace(‘/\t$/i’, ”, $output);

if ($outmode==SC_WEIRDASS_BRACES)
$output .= “\t”;

$indent = str_repeat(“\t”, $indentlevel);

$output .= $spelling;
if ($spelling==’;’||$spelling=='{‘||$spelling==’}’)
$output .= “\n$indent”;

return $output;

$sc = ‘echo “1”;if (FALSE){echo 2;
echo 2; echo 2; if( TRUE ){echo 3;}}echo 4;’;

print sc_pp($sc, 1);