简体   繁体   中英

Is there a pretty print for PHP?

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

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?

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.

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>

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.

How about print_r?

http://www.php.net/print_r

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.

记得在php.ini中设置html_errors = on ,以便与xdebug结合使用var_dump()。

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
||---------------------------------||
error_log(print_r($variable,true));

发送到Windows的syslog或eventlog

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 .

我没有看到有人提到用你的print_r命令做一个“逗号true”,然后你可以使用它与html内联,而无需通过所有的环节或提供的多杂乱的解决方案。

print "session: <br><pre>".print_r($_SESSION, true)."</pre><BR>";

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). 在此输入图像描述 Disclaimer: I wrote this myself.

A nice colored output:

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

will looks like:

在此输入图像描述

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

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

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;
}
?>

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
      (
      )...

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.

因为我发现这是通过谷歌搜索如何格式化json,使其更易于进行故障排除。

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

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

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

FirePHP是一个firefox插件,打印具有非常漂亮的日志记录功能。

    <?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

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:

在此输入图像描述

This is what i usally use:

$x= array(1,2,3);
echo "<pre>".var_export($x,1)."</pre>";

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.

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

Typical debug() html output looks like this:

在此输入图像描述

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"

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM