207

I have a simple $_GET[] query var set for showing testing data when pulling down queries from the DB.

<?php if($_GET['test']): ?>
  <div id="test" style="padding: 24px; background: #fff; text-align: center;">  
    <table>
      <tr style="font-weight: bold;"><td>MLS</td></tr>
      <tr><td><?php echo KEY; ?></td></tr>
      <tr style="font-weight: bold;"><td>QUERY</td></tr>
      <tr><td><?php echo $data_q; ?></td></tr>
      <tr style="font-weight: bold;"><td>DATA</td></tr>
      <tr><td><?php var_dump($data); ?></td></tr>
    </table>    
</div>
<?php endif; ?>

When I do var_dump, as expected it's this big array string that is all smushed together. Is there a way to add in line breaks at least for this or display the var_dump in a way that's more readable? I'm open to jQuery suggestions on manipulating the string after it's posted.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Plummer
  • 6,522
  • 13
  • 47
  • 75

16 Answers16

514

I really love var_export(). If you like copy/paste-able code, try:

echo '<pre>' . var_export($data, true) . '</pre>';

Or even something like this for color syntax highlighting:

highlight_string("<?php\n\$data =\n" . var_export($data, true) . ";\n?>");

Reusable function:

function highlight_array($array, $name = 'var') {
    highlight_string("<?php\n\$$name =\n" . var_export($array, true) . ";\n?>");
}

You can do the same with print_r(). For var_dump() you would just need to add the <pre> tags:

echo '<pre>';
var_dump($data);
echo '</pre>';
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • 8
    Note that `echo`, `var_export`, and `highlight_string` are all php functions and need to be inside a `` block. Yes even though the highlight_string function line has a pair inside, a pair is needed around the outside as well. – BeowulfNode42 Jan 10 '17 at 06:21
  • A shorter variation of this var_dump: `var_dump(highlight_string("\n". var_export($data, true)));` – jhpg Apr 05 '19 at 00:52
  • 3
    The winner in this answer is specifically `highlight_string("");`!!! – Elijah Lynn Mar 24 '21 at 00:42
51

Try xdebug extension for php.

Example:

<?php var_dump($_SERVER); ?>

Outputs:

enter image description here

Latheesan
  • 23,247
  • 32
  • 107
  • 201
  • 9
    Mind you, xdebug does ALLOT more than just pretty var_dump :) – Latheesan Nov 06 '13 at 15:55
  • I used to see like this when doing var_dump, but now that I have wampserver 2.5 with php 5.5.12 I see it unformatted. How come I could see like your photo before, without installing anything more than wampserver? – Limon Nov 28 '14 at 21:30
  • 1
    This is definitely very sexy. Not sure why this isn't marked as the correct solution, but you could give more details on the install process. On windows, it was just `extension=php_xdebug.dll`, not `zend_extension=/some/really/long/specific/path/xdebug.so` – Kraang Prime Jun 03 '15 at 15:37
38

Use preformatted HTML element

    echo '<pre>';
        var_dump($data);
    echo '</pre>';
Wael Assaf
  • 1,233
  • 14
  • 24
12

I have make an addition to @AbraCadaver answers. I have included a javascript script which will delete php starting and closing tag. We will have clean more pretty dump.

May be somebody like this too.

function dd($data){
  highlight_string("<?php\n " . var_export($data, true) . "?>");
  echo '<script>document.getElementsByTagName("code")[0].getElementsByTagName("span")[1].remove() ;document.getElementsByTagName("code")[0].getElementsByTagName("span")[document.getElementsByTagName("code")[0].getElementsByTagName("span").length - 1].remove() ; </script>';
  die();
}

Result before:

enter image description here

Result After:

enter image description here

Now we don't have php starting and closing tag

Muhammad Awais
  • 395
  • 1
  • 4
  • 15
6

I don't seem to have enough rep to close this as a duplicate, but it is one if someone else can do that. I posted the same thing over at A more pretty/informative Var_dump alternative in PHP? but for the sake of saving time, I'll copy/paste it here too:

I had to add another answer here because I didn't really want to go through the steps in the other solutions. It is extremely simple and requires no extensions, includes etc and is what I prefer. It's very easy and very fast.

First just json_encode the variable in question:

echo json_encode($theResult);

Copy the result you get into the JSON Editor at http://jsoneditoronline.org/ just copy it into the left side pane, click Copy > and it pretty prints the JSON in a really nice tree format.

To each their own, but hopefully this helps some others have one more nice option! :)

zpert
  • 706
  • 9
  • 18
6

Here's an alternative, actively maintained open source var_dump on steroids:

https://github.com/php-sage/sage

It works with zero set up and is more useable than Xdebug's var_dump and symfony/var-dumper.

Example which bypasses the dumped object size limit on the fly with Kint:

     require 'sage.phar';
     +d( $variable ); // append `+` to the dump call

Here's a screenshot:

kint

raveren
  • 17,799
  • 12
  • 70
  • 83
3

If it's "all smushed together" you can often give the ol' "view source code" a try. Sometimes the dumps, messages and exceptions seem like they're just one long string when it turns out that the line breaks simply don't show. Especially XML trees.

Alternatively, I've once created a small little tool called InteractiveVarDump for this very purpose. It certainly has its limits but it can also be very convenient sometimes. Even though it was designed with PHP 5 in mind.

WoodrowShigeru
  • 1,418
  • 1
  • 18
  • 25
2

The best what and easiest way to get nice var_dump is use xDebug (must have for any php dev) Debian way install

In console: apt-get install php-xdebug after that you should open php.ini (depends on which stack you use) for it's /etc/php/7.0/fpm/php.ini

Search for display_errors

set same -> display_errors = On

Check html_errors in same file a little bit below, it's also must be On

Save and exit

After open /etc/php/7.0/fpm/conf.d/20-xdebug.ini

And add to the end: ``` xdebug.cli_color=1

``` Save and exit.

A lot other available option and documentation for xdebug can be founded here.

https://xdebug.org/docs/

Good luck and Have Fun !!!

Result

Moris Finkel
  • 197
  • 2
  • 5
1

You could use this one debugVar() instead of var_dump()

Check out: https://github.com/E1NSER/php-debug-function

E1NSER
  • 21
  • 1
1

Here is my function to have a pretty var_dump. Combined with Xdebug, it helps a lot to have a better view of what we are dumping.

I improved a bit the display of Xdebug (give some space around, separator between values, wrap long variables, etc).

When you call the function, you can set a title, a background, a text color to distinguish all your var_dump in a page.

Or not ;)

/**
 * Pretty var_dump 
 * Possibility to set a title, a background-color and a text color
 */ 
function dump($data, $title="", $background="#EEEEEE", $color="#000000"){

    //=== Style  
    echo "  
    <style>
        /* Styling pre tag */
        pre {
            padding:10px 20px;
            white-space: pre-wrap;
            white-space: -moz-pre-wrap;
            white-space: -pre-wrap;
            white-space: -o-pre-wrap;
            word-wrap: break-word;
        }

        /* ===========================
        == To use with XDEBUG 
        =========================== */
        /* Source file */
        pre small:nth-child(1) {
            font-weight: bold;
            font-size: 14px;
            color: #CC0000;
        }
        pre small:nth-child(1)::after {
            content: '';
            position: relative;
            width: 100%;
            height: 20px;
            left: 0;
            display: block;
            clear: both;
        }

        /* Separator */
        pre i::after{
            content: '';
            position: relative;
            width: 100%;
            height: 15px;
            left: 0;
            display: block;
            clear: both;
            border-bottom: 1px solid grey;
        }  
    </style>
    ";

    //=== Content            
    echo "<pre style='background:$background; color:$color; padding:10px 20px; border:2px inset $color'>";
    echo    "<h2>$title</h2>";
            var_dump($data); 
    echo "</pre>";

}
Arno
  • 11
  • 1
1
function var_view($var)
{

    ini_set("highlight.keyword", "#a50000;  font-weight: bolder");
    ini_set("highlight.string", "#5825b6; font-weight: lighter; ");

    ob_start();
    highlight_string("<?php\n" . var_export($var, true) . "?>");
    $highlighted_output = ob_get_clean();

    $highlighted_output = str_replace( ["&lt;?php","?&gt;"] , '', $highlighted_output );

    echo $highlighted_output;
    die();
}
smarteist
  • 1,331
  • 12
  • 15
0

There is a Symfony package for this: https://symfony.com/doc/current/components/var_dumper.html.

Michael Käfer
  • 1,597
  • 2
  • 19
  • 37
0

Here is a function I made for showing arrays in a nice way:

function nicevar($var,$title=''){
    if(is_array($var)){
        $table = '<table>';
        if($title){
            $table .= '<tr><th colspan="20">'.$title.'</th></tr>';
        }
        foreach($var as $k => $v){
            $table .= '<tr>';
                $table .= '<td><b>'.$k.'</b></td>';
                $table .= '<td>';
                    if(is_array($v)){
                        $table .= nicevar($v);
                    }else{
                        $table .=  $v;
                    }
                $table .= '</td>';
            $table .= '</tr>';
        }
        $table .= '</table>';
    }else{
        $table = $var;
    }
    return $table;  
}

usage:

echo nicevar($_SESSION['debug'],'Structure of debug');

use this styling to make it nice:

<style>
body {
        padding: 30px;
}

table {
    margin: 5px;
}
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th {
    background-color: #9fff96;
}
th, td {
  padding: 2px;
  border-spacing: 2px;
}
</style>
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
Max Lumnar
  • 81
  • 1
  • 5
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 17 '21 at 12:53
  • Not sure whst you are asking me to do, since the code is self explenatory and also works if you just copy paste it in a php file. This is however my first ever post on stackoverflow, so excuse me if i missed anything obvious. – Max Lumnar Oct 18 '21 at 14:53
-1

in CI4, it's simpler to make the output prettier:

dd($this->request);

here is the result

Yusuf Abid
  • 59
  • 3
  • 1
    The OP hasn't said that they are using Code Igniter. I assume that's what you are talking about. In which case, please expand your answer, so viewers do not have to assume what you are talking about. Give a sample output. – Rohit Gupta Jul 04 '22 at 05:12
-2

I wrote a function (debug_display) which can print, arrays, objects, and file info in pretty way.

<?php
function debug_display($var,$show = false) {
    if($show) { $dis = 'block'; }else { $dis = 'none'; }
    ob_start();
    echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
        <pre>';
    if(is_bool($var)) {
        echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
    }else {
        if(FALSE == empty($var) && $var !== NULL && $var != '0') {
            if(is_array($var)) {
                echo "Number of Indexes: " . count($var) . "\n";
                print_r($var);
            } elseif(is_object($var)) {
                print_r($var);
            } elseif(@is_file($var)){
                $stat = stat($var);
                $perm = substr(sprintf('%o',$stat['mode']), -4);
                $accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
                $modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
                $change = gmdate('Y/m/d H:i:s', $stat['ctime']);
                echo "
    file path : $var
    file size : {$stat['size']} Byte
    device number : {$stat['dev']}
    permission : {$perm}
    last access time was : {$accesstime}
    last modified time was : {$modification}
    last change time was : {$change}
    ";
            }elseif(is_string($var)) {
                print_r(htmlentities(str_replace("\t", '  ', $var)));
            }  else {
                print_r($var);
            }
        }else {
            echo 'Undefined';
        }
    }
    echo '</pre>
    </div>';
    $output = ob_get_contents();
    ob_end_clean();
    echo $output;
    unset($output);
}
Michael Mior
  • 28,107
  • 9
  • 89
  • 113
Ethan.R
  • 157
  • 2
  • 16
-12

Use

echo nl2br(var_dump());

This should work ^^

Christine
  • 125
  • 8