Is there a pretty print for PHP?

Viewed 297484

I'm fixing some PHP scripts and I'm missing ruby's pretty printer. i.e.

require 'pp'
arr = {:one => 1}
pp arr

will output {:one => 1}. This even works with fairly complex objects and makes digging into an unknown script much easier. Is there some way to duplicate this functionality in PHP?

31 Answers

This is what I use to print my arrays:

<pre>
    <?php
        print_r($your_array);
    ?>
</pre>

The magic comes with the pre tag.

Both print_r() and var_dump() will output visual representations of objects within PHP.

$arr = array('one' => 1);
print_r($arr);
var_dump($arr);

For simplicity, print_r() and var_dump() can't be beat. If you want something a little fancier or are dealing with large lists and/or deeply nested data, Krumo will make your life much easier - it provides you with a nicely formatted collapsing/expanding display.

error_log(print_r($variable,true));

to send to syslog or eventlog for windows

a one-liner that will give you the rough equivalent of "viewing source" to see array contents:

assumes php 4.3.0+:

echo nl2br(str_replace(' ', ' ', print_r($_SERVER, true)));

Since I found this via google searching for how to format json to make it more readable for troubleshooting.

ob_start() ;  print_r( $json ); $ob_out=ob_get_contents(); ob_end_clean(); echo "\$json".str_replace( '}', "}\n", $ob_out );

If your server objects to you changing headers (to plain text) after some have been sent, or if you don't want to change your code, just "view source" from your browser--your text editor (even notepad) will process new lines better than your browser, and will turn a jumbled mess:

Array ( [root] => 1 [sub1] => Array ( ) [sub2] => Array ( ) [sub3] => Array ( ) [sub4] => Array ( ) ...

into a properly tabbed representation:

[root] => 1
  [sub1] => Array
      (
      )

  [sub2] => Array
      (
      )

  [sub3] => Array
      (
      )

  [sub4] => Array
      (
      )...
Related