Display output of PHP print_r in HTML

Both echo and print_r are widely used in day to day PHP programming, but raw print_r is very unfriendly to HTML display which is the de facto output interface in web developing environment.

Most PHPer may have tried at some moments in their career life to make their own version of a wrapper of print_r to make it HTML friendly. Here are some handy code that I used for my tasks, they are truly great life savers at some particular moments.

Wrap the output in a pre tag

A pre tag in HTML keeps the format of text, which means the line ending is kept. This makes the output of print_r looks in HTML exactly the same as in pure text. Suppose you have a mysql query results, which is an array of object. Instead to decorated it as a HTML table, you may simply want to display it on web page.

 
function print_rr($content, $return=false) 
{
    $output = '<div style=" resize: both; "><pre>' 
        . print_r($content, true) . '</pre></div>';
 
    if ($return) {
        return $output;
    } else {
        echo $output;
    }
} 
 

Output nested data structure as HTML tables

If the data structure is nested, HTML table is easy to read the data.

 
function myprint_r($my_array) {
    if (is_array($my_array)) {
        echo "<table border=1 cellspacing=0 cellpadding=3 width=100%>";
        echo '<tr><td colspan=2 style="background-color:#333333;"><strong><font color=white>ARRAY</font></strong></td></tr>';
        foreach ($my_array as $k => $v) {
                echo '<tr><td valign="top" style="width:40px;background-color:#F0F0F0;">';
                echo '<strong>' . $k . "</strong></td><td>";
                myprint_r($v);
                echo "</td></tr>";
        }
        echo "</table>";
        return;
    }
    echo $my_array;
}
 
 

For example, lets print a nested array

 
myprint_r(array(3,4,5,"helo", array("world", 3.0)));
 

php print_r table html