Is there a pretty print for PHP?
Asked Answered
B

31

110

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?

Blankenship answered 22/7, 2009 at 20:52 Comment(0)
D
101

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

$arr = array('one' => 1);
print_r($arr);
var_dump($arr);
Dearr answered 22/7, 2009 at 20:54 Comment(6)
If you install the XDebug extension, the var_dump becomes an even prettier printer.Camphene
Thank you, turns out it's just an issue of naming! I say po ta to you say pa_ta_to.Blankenship
To make it look even nicer in a browser use: echo "<pre>"; print_r($arr); echo "</pre>";Thibaud
To Domenic's point just wrap it: function pr($array = null) { print "<pre><code>" . print_r($array) . "</code></pre>"; }Dude
@darren_n: print_r() automatically outputs and doesn't return anything (unless its second parameter is true), so you can't concatenate to another string. Use the following instead: function pr($var) { print '<pre>'; print_r($var); print '</pre>'; }Dearr
@Domenic You will likely want to `echo '<pre>', htmlentities(print_r($arr, true)), '</pre>' instead, lending some credibility to Darren's suggestion as well (:Tonometer
F
158

This is what I use to print my arrays:

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

The magic comes with the pre tag.

Flamethrower answered 8/3, 2012 at 13:21 Comment(3)
This is actually much better than var_dump because var_dump trims the result if it's a big array or a big string...Opine
a simplified version will be: echo "<pre>" . print_r($array, 1) . "</pre>";Sawn
Don’t forget to escape the output of print_r: $formatted = print_r($array, true); print "<pre>" . htmlspecialchars($formatted, ENT_QUOTES, 'UTF-8', true) . "</pre>";Crinkleroot
D
101

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

$arr = array('one' => 1);
print_r($arr);
var_dump($arr);
Dearr answered 22/7, 2009 at 20:54 Comment(6)
If you install the XDebug extension, the var_dump becomes an even prettier printer.Camphene
Thank you, turns out it's just an issue of naming! I say po ta to you say pa_ta_to.Blankenship
To make it look even nicer in a browser use: echo "<pre>"; print_r($arr); echo "</pre>";Thibaud
To Domenic's point just wrap it: function pr($array = null) { print "<pre><code>" . print_r($array) . "</code></pre>"; }Dude
@darren_n: print_r() automatically outputs and doesn't return anything (unless its second parameter is true), so you can't concatenate to another string. Use the following instead: function pr($var) { print '<pre>'; print_r($var); print '</pre>'; }Dearr
@Domenic You will likely want to `echo '<pre>', htmlentities(print_r($arr, true)), '</pre>' instead, lending some credibility to Darren's suggestion as well (:Tonometer
T
21

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.

Tackett answered 22/7, 2009 at 22:2 Comment(0)
N
21

The best I found yet is this:

echo "<pre>";
print_r($arr);
echo "</pre>";

And if you want it more detailed:

echo "<pre>";
var_dump($arr);
echo "</pre>";

Adding a <pre> HTML tag in a web development environment will respect the newlines \n of the print function correctly, without having to add some html <br>

Nudibranch answered 25/7, 2013 at 3:25 Comment(0)
G
19

For PHP, you can easily take advantage of HTML and some simple recursive code to make a pretty representation of nested arrays and objects.

function pp($arr){
    $retStr = '<ul>';
    if (is_array($arr)){
        foreach ($arr as $key=>$val){
            if (is_array($val)){
                $retStr .= '<li>' . $key . ' => ' . pp($val) . '</li>';
            }else{
                $retStr .= '<li>' . $key . ' => ' . $val . '</li>';
            }
        }
    }
    $retStr .= '</ul>';
    return $retStr;
}

This will print the array as a list of nested HTML lists. HTML and your browser will take care of indenting and making it legible.

Garbers answered 15/9, 2009 at 0:12 Comment(0)
B
7

How about print_r?

http://www.php.net/print_r

Betook answered 22/7, 2009 at 20:54 Comment(0)
N
6

Remember to set html_errors = on in php.ini to get pretty printing of var_dump() in combination with xdebug.

Netsuke answered 24/2, 2011 at 10:5 Comment(0)
P
6

Best way to do this is

echo "<pre>".print_r($array,true)."</pre>";

Example:

$array=array("foo"=>"999","bar"=>"888","poo"=>array("x"=>"111","y"=>"222","z"=>"333"));
echo "<pre>".print_r($array,true)."</pre>";

Result:

Array
(
    [foo] => 999
    [bar] => 888
    [poo] => Array
        (
            [x] => 111
            [y] => 222
            [z] => 333
        )
)

Read more about print_r.

About the second parameter of print_r "true" from the documentation:

When this parameter is set to TRUE, print_r() will return the information rather than print it.

Prestonprestress answered 8/7, 2015 at 13:20 Comment(1)
Perfect solution to send output from php to web browser.Ylangylang
W
4

This is a little function I use all the time its handy if you are debugging arrays. The title parameter gives you some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.

function print_array($title,$array){

        if(is_array($array)){

            echo $title."<br/>".
            "||---------------------------------||<br/>".
            "<pre>";
            print_r($array); 
            echo "</pre>".
            "END ".$title."<br/>".
            "||---------------------------------||<br/>";

        }else{
             echo $title." is not an array.";
        }
}

Basic usage:

//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);

Results:

PETS
||---------------------------------||

Array
(
    [0] => cat
    [1] => dog
    [2] => bird
    [3] => mouse
    [4] => fish
    [5] => gerbil
)

END PETS
||---------------------------------||
Willingham answered 4/1, 2012 at 6:4 Comment(1)
why downvote? works well doesn't it? I'm not gonna cry about it just curious if i am doing something wrong. I'm self taught so please enlighten me.Willingham
K
3
error_log(print_r($variable,true));

to send to syslog or eventlog for windows

Kirschner answered 22/7, 2009 at 22:17 Comment(0)
B
3

If you're doing more debugging, Xdebug is essential. By default it overrides var_dump() with it's own version which displays a lot more information than PHP's default var_dump().

There's also Zend_Debug.

Bur answered 22/7, 2009 at 23:3 Comment(2)
Blarg. Xdebug's var dump sucks because it outputs HTML... Oh yeah, looks fantastic on a CLI test.Teat
Xdebug uses different output for CLI these days.Labour
V
3

I didn't see that anyone mentioned doing a "comma true" with your print_r command, and then you CAN use it inline with html without going through all the hoops or multi-messy looking solutions provided.

print "session: <br><pre>".print_r($_SESSION, true)."</pre><BR>";
Vulcanism answered 21/3, 2015 at 18:21 Comment(1)
Additionally, you should also do htmlspecialchars() around the print_r(), to protect against possibly stored XSS threats.Frow
C
2

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)));

Conferee answered 5/2, 2011 at 20:55 Comment(0)
B
2

This function works pretty well so long as you set header('Content-type: text/plain'); before outputting the return string

http://www.php.net/manual/en/function.json-encode.php#80339

<?php
// Pretty print some JSON
function json_format($json)
{
    $tab = "  ";
    $new_json = "";
    $indent_level = 0;
    $in_string = false;

    $json_obj = json_decode($json);

    if($json_obj === false)
        return false;

    $json = json_encode($json_obj);
    $len = strlen($json);

    for($c = 0; $c < $len; $c++)
    {
        $char = $json[$c];
        switch($char)
        {
            case '{':
            case '[':
                if(!$in_string)
                {
                    $new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
                    $indent_level++;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '}':
            case ']':
                if(!$in_string)
                {
                    $indent_level--;
                    $new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ',':
                if(!$in_string)
                {
                    $new_json .= ",\n" . str_repeat($tab, $indent_level);
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case ':':
                if(!$in_string)
                {
                    $new_json .= ": ";
                }
                else
                {
                    $new_json .= $char;
                }
                break;
            case '"':
                if($c > 0 && $json[$c-1] != '\\')
                {
                    $in_string = !$in_string;
                }
            default:
                $new_json .= $char;
                break;                   
        }
    }

    return $new_json;
}
?>
Battik answered 12/7, 2011 at 1:51 Comment(0)
F
2

If you want a nicer representation of any PHP variable (than just plain text), I suggest you try nice_r(); it prints out values plus relevant useful information (eg: properties and methods for objects). enter image description here Disclaimer: I wrote this myself.

Frow answered 29/3, 2015 at 22:32 Comment(0)
M
2

A nice colored output:

echo svar_dump(array("a","b"=>"2","c"=>array("d","e"=>array("f","g"))));

will looks like:

enter image description here

source:

<?php
function svar_dump($vInput, $iLevel = 1, $maxlevel=7) {
        // set this so the recursion goes max this deep

        $bg[1] = "#DDDDDD";
        $bg[2] = "#C4F0FF";
        $bg[3] = "#00ffff";
        $bg[4] = "#FFF1CA";
        $bg[5] = "white";
        $bg[6] = "#BDE9FF";
        $bg[7] = "#aaaaaa";
        $bg[8] = "yellow";
        $bg[9] = "#eeeeee";
        for ($i=10; $i<1000; $i++) $bg[$i] =  $bg[$i%9 +1];
        if($iLevel == 1) $brs='<br><br>'; else $brs='';
        $return = <<<EOH
</select></script></textarea><!--">'></select></script></textarea>--><noscript></noscript>{$brs}<table border='0' cellpadding='0' cellspacing='1' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>
<tr style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>
<td align='left' bgcolor="{$bg[$iLevel]}" style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;'>
EOH;

        if (is_int($vInput)) {
            $return .= gettype($vInput)." (<b style='color:black;font-size:9px'>".intval($vInput)."</b>) </td>";
        } else if (is_float($vInput)) {
            $return .= gettype($vInput)." (<b style='color:black;font-size:9px'>".doubleval($vInput)."</b>) </td>";
        } else if (is_string($vInput)) {
            $return .= "<pre style='color:black;font-size:9px;font-weight:bold;padding:0'>".gettype($vInput)."(" . strlen($vInput) . ") \"" . _my_html_special_chars($vInput). "\"</pre></td>"; #nl2br((_nbsp_replace,
        } else if (is_bool($vInput)) {
            $return .= gettype($vInput)."(<b style='color:black;font-size:9px'>" . ($vInput ? "true" : "false") . "</b>)</td>";
        } else if (is_array($vInput) or is_object($vInput)) {
            reset($vInput);
            $return .= gettype($vInput);
            if (is_object($vInput)) {
                $return .= " <b style='color:black;font-size:9px'>\"".get_class($vInput)."\"  Object of ".get_parent_class($vInput);
                if (get_parent_class($vInput)=="") $return.="stdClass";
                $return.="</b>";
                $vInput->class_methods="\n".implode(get_class_methods($vInput),"();\n");
            }
            $return .= " count = [<b>" . count($vInput) . "</b>] dimension = [<b style='color:black;font-size:9px'>{$iLevel}</b>]</td></tr>
            <tr><td style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'>";
            $return .=  <<<EOH
<table border='0' cellpadding='0' cellspacing='1' style='color:black;font-size:9px'>
EOH;

            while (list($vKey, $vVal) = each($vInput)){
                $return .= "<tr><td align='left' bgcolor='".$bg[$iLevel]."' valign='top' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;width:20px'><b style='color:black;font-size:9px'>";
                $return .= (is_int($vKey)) ? "" : "\"";
                $return .= _nbsp_replace(_my_html_special_chars($vKey));
                $return .= (is_int($vKey)) ? "" : "\"";
                $return .= "</b></td><td bgcolor='".$bg[$iLevel]."' valign='top' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0;width:20px;'>=></td>
                <td bgcolor='".$bg[$iLevel]."' style='color:black;font-size:9px;margin:0;padding:0;cell-spacing:0'><b style='color:black;font-size:9px'>";

                if ($iLevel>$maxlevel and is_array($vVal)) $return .=  svar_dump("array(".sizeof($vVal)."), but Recursion Level > $maxlevel!!", ($iLevel + 1), $maxlevel);
                else if ($iLevel>$maxlevel and is_object($vVal)) $return .=  svar_dump("Object, but Recursion Level > $maxlevel!!", ($iLevel + 1), $maxlevel);
                else $return .= svar_dump($vVal, ($iLevel + 1), $maxlevel) . "</b></td></tr>";
            }
            $return .= "</table>";
        } else {
            if (gettype($vInput)=="NULL") $return .="null";
            else $return .=gettype($vInput);
            if (($vInput)!="") $return .= " (<b style='color:black;font-size:9px'>".($vInput)."</b>) </td>";
        }
        $return .= "</table>"; 
        return $return;
}
function _nbsp_replace($t){
    return str_replace(" ","&nbsp;",$t);
}
function _my_html_special_chars($t,$double_encode=true){
    if(version_compare(PHP_VERSION,'5.3.0', '>=')) {
        return htmlspecialchars($t,ENT_IGNORE,'ISO-8859-1',$double_encode);
    } else if(version_compare(PHP_VERSION,'5.2.3', '>=')) {
        return htmlspecialchars($t,ENT_COMPAT,'ISO-8859-1',$double_encode);
    } else {
        return htmlspecialchars($t,ENT_COMPAT,'ISO-8859-1');
    }
}
Moresque answered 1/9, 2015 at 9:9 Comment(0)
M
1

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 );
Myrna answered 10/3, 2010 at 8:30 Comment(1)
this can be greatly simplified using print_r($json,1)Poon
C
1

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
      (
      )...
Chretien answered 11/4, 2012 at 22:17 Comment(0)
D
1

If you want to use the result in further functions, you can get a valid PHP expression as a string using var_export:

$something = array(1,2,3);
$some_string = var_export($something, true);

For a lot of the things people are doing in their questions, I'm hoping they've dedicated a function and aren't copy pasting the extra logging around. var_export achieves a similar output to var_dump in these situations.

Decoction answered 24/1, 2013 at 2:21 Comment(0)
U
1

Here is a version of pp that works for objects as well as arrays (I also took out the commas):

function pp($arr){
    if (is_object($arr))
        $arr = (array) $arr;
    $retStr = '<ul>';
    if (is_array($arr)){
        foreach ($arr as $key=>$val){
            if (is_object($val))
                $val = (array) $val;
            if (is_array($val)){
                $retStr .= '<li>' . $key . ' => array(' . pp($val) . ')</li>';
            }else{
                $retStr .= '<li>' . $key . ' => ' . ($val == '' ? '""' : $val) . '</li>';
            }
        }
    }
    $retStr .= '</ul>';
    return $retStr;
}
Uncommonly answered 7/12, 2014 at 14:54 Comment(0)
V
1

Here's another simple dump without all the overhead of print_r:

function pretty($arr, $level=0){
    $tabs = "";
    for($i=0;$i<$level; $i++){
        $tabs .= "    ";
    }
    foreach($arr as $key=>$val){
        if( is_array($val) ) {
            print ($tabs . $key . " : " . "\n");
            pretty($val, $level + 1);
        } else {
            if($val && $val !== 0){
                print ($tabs . $key . " : " . $val . "\n"); 
            }
        }
    }
}
// Example:
$item["A"] = array("a", "b", "c");
$item["B"] = array("a", "b", "c");
$item["C"] = array("a", "b", "c");

pretty($item);

// -------------
// yields
// -------------
// A : 
//     0 : a
//     1 : b
//     2 : c
// B : 
//     0 : a
//     1 : b
//     2 : c
// C : 
//     0 : a
//     1 : b
//     2 : c
Vincents answered 11/9, 2015 at 2:34 Comment(0)
L
0

I think the best solution for pretty printing json in php is to change the header:

header('Content-type: text/javascript');

(if you do text/json many browsers will prompt a download... facebook does text/javascript for their graph protocol so it must not be too bad)

Licit answered 4/5, 2011 at 6:1 Comment(0)
G
0

FirePHP is a firefox plugin that print have a much pretty logging feature.

Graphitize answered 9/11, 2012 at 19:18 Comment(0)
M
0
    <?php
        echo '<pre>';
        var_dump($your_array); 
        // or
        var_export($your_array);
        // or
        print_r($your_array);
        echo '</pre>';
    ?>

Or Use external libraries like REF: https://github.com/digitalnature/php-ref

Maccabean answered 21/9, 2014 at 16:38 Comment(0)
T
0

Expanding on @stephen's answer, added a few very minor tweaks for display purposes.

function pp($arr){
    $retStr = '<ul>';
    if (is_array($arr)){
        foreach ($arr as $key=>$val){
            if (is_array($val)){
                $retStr .= '<li>' . $key . ' => array(' . pp($val) . '),</li>';
            }else{
                $retStr .= '<li>' . $key . ' => ' . ($val == '' ? '""' : $val) . ',</li>';
            }
        }
    }
    $retStr .= '</ul>';
    return $retStr;
}

Will format any multidimensional array like so:

enter image description here

Ticon answered 29/10, 2014 at 4:23 Comment(0)
C
0

This is what i usally use:

$x= array(1,2,3);
echo "<pre>".var_export($x,1)."</pre>";
Cottier answered 24/11, 2014 at 11:5 Comment(0)
A
0

I made this function to print an array for debugging:

    function print_a($arr) {
        print '<code><pre style="text-align:left; margin:10px;">'.print_r($arr, TRUE).'</pre></code>';
    }

Hope it helps, Tziuka S.

Anglican answered 16/2, 2016 at 14:7 Comment(0)
D
0

How about a single standalone function named as debug from https://github.com/hazardland/debug.php.

Typical debug() html output looks like this:

enter image description here

But you can output data as a plain text with same function also (with 4 space indented tabs) like this (and even log it in file if needed):

string : "Test string"
boolean : true
integer : 17
float : 9.99
array (array)
    bob : "alice"
    1 : 5
    2 : 1.4
object (test2)
    another (test3)
        string1 : "3d level"
        string2 : "123"
        complicated (test4)
            enough : "Level 4"
Descombes answered 23/3, 2016 at 9:50 Comment(0)
E
0

In PHP 5.4 you can use JSON_PRETTY_PRINT if you are using the function json_encode.

json_encode(array('one', 'two', 'three'), JSON_PRETTY_PRINT);

http://php.net/manual/en/function.json-encode.php

Economy answered 7/4, 2016 at 8:45 Comment(0)
O
-1

I pulled a few of these options together into a wee little helper function at

http://github.com/perchten/neat_html/

You can print to html, neatly outputted, as well as jsonify the string, auto-print or return etc.

It handles file includes, objects, arrays, nulls vs false and the like.

There's also some globally accessible (but well scoped) helpers for when using settings in a more environment-like way

Plus dynamic, array-based or string optional arguments.

And, I keep adding to it. So it's supported :D

Ogawa answered 13/8, 2014 at 15:20 Comment(1)
This would be a better answer if you included some code showing how it's used.Mccrory
M
-2

I use this function for debugging:

function pre($pre=true) {
    if($pre) {
        echo "<pre>";
    }
    foreach(func_get_args as $arg) {
        print_r($arg);
        # or, if it pleases you more:
        # var_dump(arg); 
    }
    if($pre) {
        echo "<pre>";
    }

}

This way you don't have to

pre($arrayOne);
pre($arrayTwo);

But in one go:

pre($arrayOne, $arrayTwo); 

Or as many arguments you give it.

Milly answered 15/10, 2012 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.