Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I theme print_r into collapsible rows?

Tags:

php

Doing print_r, returns pages and pages of code; it's too hard to scroll pages to match children to parents, even wrapped with <pre> tags.

Is there a way to theme print_r into collapsible fields. Maybe an online generator, where I can post the contents of the print_r($array); and get a collapsible table of fields.

For example, in Drupal, there's a module, called Devel, that does just that. Devel Screenshot

like image 282
timofey.com Avatar asked Oct 02 '12 20:10

timofey.com


3 Answers

Unless I am missing something, the answer is in your screenshot: http://krumo.sourceforge.net/

EDIT (2019): Try https://github.com/kint-php/kint as it is still maintained today.

like image 77
deizel Avatar answered Oct 10 '22 22:10

deizel


Thanks to this post, here's a solution.

Insert the following function, right before the print_r.

<?php
function print_r_tree($data)
{
    // capture the output of print_r
    $out = print_r($data, true);

    // replace something like '[element] => <newline> (' with <a href="javascript:toggleDisplay('...');">...</a><div id="..." style="display: none;">
    $out = preg_replace('/([ \t]*)(\[[^\]]+\][ \t]*\=\>[ \t]*[a-z0-9 \t_]+)\n[ \t]*\(/iUe',"'\\1<a href=\"javascript:toggleDisplay(\''.(\$id = substr(md5(rand().'\\0'), 0, 7)).'\');\">\\2</a><div id=\"'.\$id.'\" style=\"display: none;\">'", $out);

    // replace ')' on its own on a new line (surrounded by whitespace is ok) with '</div>
    $out = preg_replace('/^\s*\)\s*$/m', '</div>', $out);

    // print the javascript function toggleDisplay() and then the transformed output
    echo '<script language="Javascript">function toggleDisplay(id) { document.getElementById(id).style.display = (document.getElementById(id).style.display == "block") ? "none" : "block"; }</script>'."\n$out";
}
?>

And then, substitute print_r(), with print_r_tree(); like this:

<pre><?php echo print_r_tree(get_defined_vars()); ?></pre>

Don't forget the <pre> tags.

The results look identical to that of print_r() function, except that now the arrays are collapsible.

like image 20
timofey.com Avatar answered Oct 11 '22 00:10

timofey.com


Why not ouput it as JSON and then paste it on http://jsonviewer.stack.hu/, which makes it readible AND collapsible!

json_encode($array);

Example: enter image description here

like image 27
edwardmp Avatar answered Oct 11 '22 00:10

edwardmp