PHP: Improving print_r() with print_pre() Wrapper Function

When you need a simple debugging function and print_r() is just not enough, you need a good wrapper function. You need print_pre().

Most print_pre() functions out there just wrap the print_r() output with the <pre> tag. Useful, but not that useful. This print_pre() function has evolved over the time I have used it. I have used it across multiple jobs. Where it is now is good, anything added to it would be for specialized cases.

This print_pre() function does a bit more than just wrap the print_r() with <pre> tags. Sometimes you may not be able to view any output easily, so it may output to a file if you so desire. It can be used in place of any print_r() as it may be used exactly the same. Another cool feature is word wrapping, which basically does away with the <pre> tag and wraps it in a <p><tt> combo.

function print_pre ($expression, $return = false, $wrap = false)
{
  $css = 'border:1px dashed #06f;background:#69f;padding:1em;text-align:left;';
  if ($wrap) {
    $str = '<p style="' . $css . '"><tt>' . str_replace(
      array('  ', "\n"), array('&nbsp; ', '<br />'),
      htmlspecialchars(print_r($expression, true))
    ) . '</tt></p>';
  } else {
    $str = '<pre style="' . $css . '">'
    . htmlspecialchars(print_r($expression, true)) . '</pre>';
  }
  if ($return) {
    if (is_string($return) && $fh = fopen($return, 'a')) {
      fwrite($fh, $str);
      fclose($fh);
    }
    return $str;
  } else
    echo $str;
}

The print_pre() function has simple usage:

mixed print_pre (mixed $expression [, mixed $return = false [, bool $wrap = false ]] )

The second parameter, return, works just like the return parameter on print_r() except when a non-empty string is passed. If a string is passed to the return parameter, it will be treated as a file path to save the output to and will continue to return the output. The last parameter, wrap, is rather self explanatory; it will allow long lines to break and the text will not be preformatted if set to TRUE.

Everybody likes examples, so here are a few for you:

// Let us assume print_pre() and $obj were defined before this point

print_pre($obj);
// the output is simply printed

$string = print_pre($obj,true);
// $string contains the output

echo print_pre($obj,'debug.htm',true);
// the output allows wrapping, is saved to debug.htm and then printed

And that is the print_pre() function. Ok, my print_pre() function. Enjoy!