Every decent PHP programmer has a print_r
or var_dump
wrapper they use, love and assign shortcut keys to, why don't we share our favourite ones.
每个优秀的PHP程序员都有一个他们使用的print_r或var_dump包装器,喜欢并分配快捷键,为什么我们不共享我们最喜欢的呢?
23 个解决方案
#1
66
A full year of time and labor after asking this, I've finally open sourced my version of var_dump, Kint. Read about it in the project page, or directly in github.
问了这个问题之后,我花了整整一年的时间和精力终于打开了我版本的var_dump Kint。在项目页面或github上直接阅读。
Here's a screenshot:
这里有一个截图:
Sorry for the plug :)
对不起,插头:)
EDIT: I'd just like to remind the commenters, that this is not a support forum, if you're having problems/want a feature, please file an issue. Support requesting comments will be flagged for deletion.
编辑:我只是想提醒评论者,这不是一个支持论坛,如果你有问题/想要一个功能,请提交一个问题。支持请求注释将被标记为删除。
#2
43
My prefered on is the var_dump
function, as provided by the Xdebug extension : just install the extension (easy, both on windows and Linux), and var_dump
gets a better output :
我更喜欢的是v_dump函数,由Xdebug扩展提供:只需安装扩展(在windows和Linux上都很容易),var_dump得到更好的输出:
- better formating
- HTML
- HTML
- colors
- 颜色
- 更好的使格式化HTML的颜色
- and you have options to tune how much informations should be displayed
- 你可以选择调整显示多少信息
And a quick screenshot :
还有一个快速的截图:
And, of course, Xdebug brings loads of other usefull stuff, like remote debugging (i.e. graphical debugging of your PHP application, in Eclipse PDT for instance), profiling, ...
当然,Xdebug会带来很多其他有用的东西,比如远程调试(例如,在Eclipse PDT中对PHP应用程序进行图形化调试)、分析……
#3
#4
24
Here's mine, which I use inline, very useful:
这是我的,我使用内联,非常有用:
$pretty = function($v='',$c=" ",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'<NULL>':"<strong>$v</strong>");}return$r;};
echo $pretty($some_variable);
#5
16
You are looking for Krumo (Warning, Chrome alerts for Malware).
您正在寻找Krumo(警告,恶意软件的Chrome警告)。
To put it simply, Krumo is a replacement for print_r() and var_dump(). By definition Krumo is a debugging tool (initially for PHP4/PHP5, now for PHP5 only), which displays structured information about any PHP variable.
简单地说,Krumo是print_r()和var_dump()的替代品。根据定义,Krumo是一个调试工具(最初用于PHP4/PHP5,现在只用于PHP5),它显示关于任何PHP变量的结构化信息。
#6
9
我喜欢Firephp + firebug
- It writes the logging information out using headers, so it doesn't break AJAX.
- 它使用头文件来写日志信息,所以它不会破坏AJAX。
- Gives you a very nice graphical representation of the variables/objects you log
- 为您提供了一个非常好的您所记录的变量/对象的图形表示
- Can display file name and line number where each log statement occurs
- 是否可以在出现每个日志语句的地方显示文件名和行号
- Easy to use in your project, either with a procedural or object-oriented API
- 易于在项目中使用,无论是使用过程API还是面向对象API
#7
8
My (partial) solution for this is the simply add a function like this (using Google Chrome):
我的(部分)解决方案是简单地添加这样的函数(使用谷歌Chrome):
<?
function console_dump($value)
{
?>
<script>
console.log(<? echo json_encode($value); ?>);
</script>
<?
}
?>
Press Ctrl + Shift + J (opens up the console), and you can find there the JSON structure. Even more useful for a pretty print of JSON responses ofcourse.
按Ctrl + Shift + J(打开控制台),您可以在那里找到JSON结构。当然,对于漂亮打印JSON响应更有用。
#8
7
I've been using dBug, which emulates Coldfusion's awesome cfdump
tag:
我一直在使用dBug,它模仿Coldfusion超棒的cfdump标签:
http://dbug.ospinto.com/examples.php
http://dbug.ospinto.com/examples.php
#9
7
A complete example of what I use ...
我用的一个完整的例子……
<pre>
<?php
//*********** Set up some sample data
$obj = new stdClass;
$obj->a=123;
$obj->pl=44;
$obj->l=array(31,32);
$options = array(
'Orchestra'=>array(1=>'Strings', 8=>'Brass', 9=>$obj, 3=>'Woodwind', 16=>'Percussion'),
2=>'Car',
4=>'Bus',
'TV'=>array(21=>'Only Fools', 215=>'Brass Eye', 23=>'Vic Bob',44=>null, 89=>false));
//*********** Define the function
function dump($data, $indent=0) {
$retval = '';
$prefix=\str_repeat(' | ', $indent);
if (\is_numeric($data)) $retval.= "Number: $data";
elseif (\is_string($data)) $retval.= "String: '$data'";
elseif (\is_null($data)) $retval.= "NULL";
elseif ($data===true) $retval.= "TRUE";
elseif ($data===false) $retval.= "FALSE";
elseif (is_array($data)) {
$retval.= "Array (".count($data).')';
$indent++;
foreach($data AS $key => $value) {
$retval.= "\n$prefix [$key] = ";
$retval.= dump($value, $indent);
}
}
elseif (is_object($data)) {
$retval.= "Object (".get_class($data).")";
$indent++;
foreach($data AS $key => $value) {
$retval.= "\n$prefix $key -> ";
$retval.= dump($value, $indent);
}
}
return $retval;
}
//*********** Dump the data
echo dump($options);
?>
</pre>
Outputs ...
输出……
Array (4)
[Orchestra] = Array (5)
| [1] = String: 'Strings'
| [8] = String: 'Brass'
| [9] = Object (stdClass)
| | a -> Number: 123
| | pl -> Number: 44
| | l -> Array (2)
| | | [0] = Number: 31
| | | [1] = Number: 32
| [3] = String: 'Woodwind'
| [16] = String: 'Percussion'
[2] = String: 'Car'
[4] = String: 'Bus'
[TV] = Array (5)
| [21] = String: 'Only Fools'
| [215] = String: 'Brass Eye'
| [23] = String: 'Vic Bob'
| [44] = NULL
| [89] = FALSE
#10
6
Here is mine:
这是我的:
public function varToHtml($var='', $key='') {
$type = gettype($var);
$result = '';
if (in_array($type, array('object','array'))) {
$result .= '
<table class="debug-table">
<tr>
<td class="debug-key-cell"><b>'.$key.'</b><br/>Type: '.$type.'<br/>Length: '.count($var).'</td>
<td class="debug-value-cell">';
foreach ($var as $akey => $val) {
$result .= sbwDebug::varToHtml($val, $akey);
}
$result .= '</td></tr></table>';
} else {
$result .= '<div class="debug-item"><span class="debug-label">'.$key.' ('.$type.'): </span><span class="debug-value">'.$var.'</span></div>';
}
return $result;
}
Styled with:
风格:
table.debug-table {
padding: 0;
margin: 0;
font-family: arial,tahoma,helvetica,sans-serif;
font-size: 11px;
}
td.debug-key-cell {
vertical-align: top;
padding: 3px;
border: 1px solid #AAAAAA;
}
td.debug-value-cell {
vertical-align: top;
padding: 3px;
border: 1px solid #AAAAAA;
}
div.debug-item {
border-bottom: 1px dotted #AAAAAA;
}
span.debug-label {
font-weight: bold;
}
#11
5
I recently developed a free chrome extension (work in progress) in order to beautify my var dumps with no libraries, no pre tags and no installation to each and every app. All done with JavaScript and regEx. All you have to do is install the extension and your good to go. I am working on a Firefox version as well. Here is the GitHub page. I hope to have it available on the chrome and firefox webstores soon!
我最近开发了一个免费的chrome扩展(正在开发中),以美化我的var转储,没有库、没有前置标签,也没有安装每个应用程序。你所要做的就是安装扩展,然后你就可以离开了。我也正在开发一个Firefox版本。这是GitHub的页面。我希望它能很快在chrome和火狐网络商店上使用!
https://github.com/alexnaspo/var_dumpling
https://github.com/alexnaspo/var_dumpling
Here is an example output:
这里有一个输出示例:
#13
1
Those fancy libraries are great ... except the overhead. If you want a simple, pretty var_dump that takes infinite parameters, try my function. It adds some simple HTML. Data attributes are added too, if you use HTML5, lower versions will just ignore them, but makes it easy to open element in browser console and get a little more info if what you see on screen is not enough.
那些漂亮的图书馆很棒……除了开销。如果您想要一个简单的、漂亮的、具有无限参数的var_dump,请尝试我的函数。它添加了一些简单的HTML。数据属性也被添加,如果你使用HTML5,低级版本会忽略它们,但是如果你在屏幕上看到的还不够的话,打开浏览器控制台的元素并获得更多的信息是很容易的。
The layout is very simple, no overhead. Provides a ton of info for each parameter including things like gettype
and even class
name for Object dumps (including XML). It's tried and true, I've been using it for years.
布局非常简单,没有开销。为每个参数提供大量信息,包括gettype,甚至对象转储的类名(包括XML)。这是事实,我已经用了很多年了。
function preDump() { // use string "noEcho" to just get a string return only
$args = func_get_args();
$doEcho = TRUE; $sb;
if ($args) {
$sb = '<div style="margin: 1em 0;"><fieldset style="display:inline-block;padding:0em 3em 1em 1em;"><legend><b>preDump: '.count($args).' Parameters Found.</b></legend>';
foreach (func_get_args() as $arg) {
if (gettype($arg) == 'string') if ($arg == 'noEcho') { $doEcho = FALSE; $sb = preg_replace('/(preDump: )[0-9]+/', 'preDump: '.(count($args)-1), $sb); continue; }
$sb .= '<pre data-type="'.gettype($arg).'"';
switch (gettype($arg)) {
case "boolean":
case "integer":
$sb .= ' data-dump="json_encode"><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')</b></p><p>';
$sb .= json_encode($arg);
break;
case "string":
$sb .= ' data-dump="echo"><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')</b></p><p>';
$sb .= $arg;
break;
default:
$sb .= ' data-dump="var_dump"';
if (is_object($arg)) $sb .= 'data-class="'.get_class($arg).'"';
$sb .= '><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')';
if (is_object($arg)) $sb .= ' ['.get_class($arg).']';
$sb .= '</b></p><p>';
ob_start();
var_dump($arg);
$sb .= ob_get_clean();
if (ob_get_length()) ob_end_clean();
}
$sb .= '</p></pre>';
}
$sb .= '</fieldset></div>';
}
else {
$sb = '<div style="margin: 1em 0;"><fieldset style="display:inline-block;"><legend><b>preDump: [ERROR]</b></legend><h3>No Parameters Found</h3></fieldset></div>';
}
if ($doEcho) echo($sb);
return $sb;
}
And If you use Codeigniter, add it too your CI EXTREMELY SIMPLY. First, go to application/config/autoload.php
and make sure the helper
'string'
is on.
如果你使用Codeigniter,添加它也非常简单。首先,去应用程序/配置/自动装载。php,并确保助手“字符串”是打开的。
$autoload['helper'] = array( 'string' );
Then simply go create a file named MY_string_helper.php
in application/helpers
and simple insert the function in a typical if
statement for existence check.
然后创建一个名为MY_string_helper的文件。php在应用程序/助手和简单插入函数在一个典型的if语句中进行存在检查。
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
if (!function_exists('preDump')) {
function preDump() {
...
}
}
// DON'T CLOSE PHP
|OR|, if you want to take it a different direction.
|或者|,如果你想换个方向。
The following snippet is the same as above, except will show your variables in the browser console. This can sometimes make it easier to debug sql object calls and other array and object calls where you're missing the key name or whatever.
下面的代码片段与上面的代码片段相同,只是将在浏览器控制台显示变量。这有时可以使调试sql对象调用和其他数组和对象调用更容易,在这些调用中您将丢失键名或其他名称。
function consoleDump() { // use string "noEcho" to just get a string return only
$args = func_get_args();
$doEcho = TRUE; $sb;
if ($args) {
$sb = '<script type="text/javascript">console.log("<" + new Array('.(count($args) < 10 ? '49': '48').').join("-") + "[consoleDump: '.count($args).' items]" + new Array(50).join("-") + ">"); console.log([';
foreach (func_get_args() as $i => $arg) {
if (gettype($arg) == 'string') if ($arg == 'noEcho') { $doEcho = FALSE; $sb = preg_replace('/(consoleDump: )[0-9]+/', 'consoleDump: '.(count($args)-1), $sb); continue; }
$sb .= '{ "type": "'.gettype($arg).'", ';
switch (gettype($arg)) {
case "boolean":
case "integer":
case "string":
$sb .= '"value": '.json_encode($arg);
break;
default:
$sb .= '"value": '.json_encode($arg);
if (is_object($arg) || is_array($arg)) $sb .= ', "count": '.json_encode(count((array)$arg));
if (is_object($arg)) $sb .= ', "objectClass": "'.get_class($arg).'"';
}
$sb .= '}';
if ($i < count($args)-1) $sb .= ', ';
}
$sb .= ']); console.log("<" + new Array(120).join("-") + ">"); </script>';
}
else {
$sb = '<script type="text/javascript">console.log("<" + new Array(120).join("-") + ">");console.log("consoleDump: [ERROR] No Parameters Found");console.log("<" + new Array(120).join("-") + ">");</script>';
}
if ($doEcho) echo($sb);
return $sb;
}
Works with everything!
适用于一切!
consoleDump($simpXMLvar, $_SESSION, TRUE, NULL, array( 'one' => 'bob', 'two' => 'bill' ), (object)array( 'one' => 'bob', 'two' => 'bill' ));
<------------------------------------------------[consoleDump: 6 items]------------------------------------------------->
[Object, Object, Object, Object, Object, Object]
// This drops down to show your variables in JS objects, like:
0: Object
count: 4
objectClass: "SimpleXMLElement"
type: "object"
value: Object
__proto__: Object
// ...etc...
<----------------------------------------------------------------------------------------------------------------------->
#14
1
To make the list more complete - Symfony developers released a usable-as-standalone dumper alternative:
为了使列表更完整,Symfony开发人员发布了一个可用的作为独立的翻斗车替代品:
https://github.com/symfony/var-dumper
https://github.com/symfony/var-dumper
You can read about it more here:
你可以在这里读到更多:
http://www.sitepoint.com/var_dump-introducing-symfony-vardumper/
http://www.sitepoint.com/var_dump-introducing-symfony-vardumper/
#15
0
I wrote small class that is similar to Krumo, but much easier to embed to app.
我写了一个类似Krumo的小类,但是更容易嵌入到app中。
Here is link: https://github.com/langpavel/PhpSkelet/blob/master/Classes/Debug.php
这是链接:https://github.com/langpavel/PhpSkelet/blob/master/Classes/Debug.php
And here sample output: http://langpavel.php5.cz/debug_sample.html
这里是示例输出:http://langpavel.php5.cz/debug_sample.html
#16
0
PHP Array Beautifier This simple tool takes an array or object output in PHP, such as a print_r() statement and formats it in color coding to easily read your data. http://phillihp.com/toolz/php-array-beautifier/
这个简单的工具使用PHP中的数组或对象输出,例如print_r()语句,并将其格式化为彩色代码,以便轻松读取数据。http://phillihp.com/toolz/php-array-beautifier/
#17
0
Yet another home-grown version:
另一个本土版:
http://github.com/perchten/neat_html
http://github.com/perchten/neat_html
I like to think it's pretty flexible. It doesn't aim for particular output environment but has a bunch of optional arguments you can specify why change the output/print or behaviour, as well as some persistent settings.
我认为它很灵活。它不针对特定的输出环境,但是有许多可选参数,您可以指定为什么要更改输出/打印或行为,以及一些持久设置。
#18
0
Here is a chrome extension that I wrote to solve this problem.
这是我为解决这个问题而编写的chrome扩展。
https://chrome.google.com/webstore/detail/varmasterpiece/chfhddogiigmfpkcmgfpolalagdcamkl
https://chrome.google.com/webstore/detail/varmasterpiece/chfhddogiigmfpkcmgfpolalagdcamkl
#19
0
I developed a chrome extension and jquery plugin in order to beautify var_dumps
我开发了一个chrome扩展和jquery插件来美化var_dumps
https://github.com/netfox01/fleX-debug
https://github.com/netfox01/fleX-debug
#20
0
My preferred is debug from https://github.com/hazardland/debug.php which is library with containing only single function named as debug (You can just copy that function in your project or in your library). Typical debug() html output looks like this:
我更喜欢使用https://github.com/gifland/debug.php进行调试,它是一个只包含一个名为debug的函数的库(您可以在项目或库中复制该函数)。典型的debug() html输出如下所示:
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):
但是,您可以将数据作为具有相同功能的纯文本(有4个空格缩进的选项卡)输出(如果需要,甚至可以在文件中记录):
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"
#21
0
If you're dealing with very big arrays in PHP, this function may help:
如果在PHP中处理非常大的数组,这个函数可能会有所帮助:
function recursive_print ($varname, $varval) {
if (! is_array($varval)):
print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
else:
print $varname . " = array();<br>\n";
foreach ($varval as $key => $val):
recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
endforeach;
endif;
}
It basically dumps the whole array where each element is in separate line, which is beneficial to find the right full paths for certain elements.
它基本上转储整个数组,其中每个元素都在单独的行中,这有利于为某些元素找到正确的完整路径。
Example output:
示例输出:
$a = array();
$a[0] = 1;
$a[1] = 2;
$a[2] = array();
$a[2][0] = 'a';
$a[2][1] = 'b';
$a[2][2] = 'c';
See: How to export PHP array where each key-value pair is in separate line?
参见:如何导出每个键值对在单独一行中的PHP数组?
#22
0
I'm surprised nobody mentioned the easiest (albeit not very pretty) code. If you just want to get a readable output (no colors or indentation), a simple <pre>
around a var_dump
works, as in:
我很惊讶没有人提到最简单(虽然不是很漂亮)的代码。如果您只想获得一个可读的输出(没有颜色或缩进),那么在var_dump前后使用一个简单的
就可以了,如下所示:
echo "<pre>";
var_dump($myvariable);
echo "</pre>";
Can't get much lower overhead than this!
没有比这更低的开销了!
#23
-1
TVarDumper
This is a great tool which is intended to replace the buggy PHP function var_dump
and print_r
, since it can correctly identify the recursively referenced objects in a complex object structure. It also has a recursive depth control to avoid indefinite recursive display of some peculiar variables.
这是一个很好的工具,用于替换有bug的PHP函数var_dump和print_r,因为它可以在复杂的对象结构中正确地标识递归引用的对象。它还具有递归深度控制,以避免某些特殊变量的无限递归显示。
See: TVarDumper.php
.
看到:TVarDumper.php。
For other alternative solutions which provides more advantages over var_dump
and print_r
and can support circular references, please check: Using print_r and var_dump with circular reference.
对于其他替代解决方案,它们比var_dump和print_r具有更大的优势,并且可以支持循环引用,请检查:使用print_r和var_dump并使用循环引用。
For more ideas, check also: How do you debug PHP scripts?
要了解更多的想法,还可以检查:如何调试PHP脚本?
#1
66
A full year of time and labor after asking this, I've finally open sourced my version of var_dump, Kint. Read about it in the project page, or directly in github.
问了这个问题之后,我花了整整一年的时间和精力终于打开了我版本的var_dump Kint。在项目页面或github上直接阅读。
Here's a screenshot:
这里有一个截图:
Sorry for the plug :)
对不起,插头:)
EDIT: I'd just like to remind the commenters, that this is not a support forum, if you're having problems/want a feature, please file an issue. Support requesting comments will be flagged for deletion.
编辑:我只是想提醒评论者,这不是一个支持论坛,如果你有问题/想要一个功能,请提交一个问题。支持请求注释将被标记为删除。
#2
43
My prefered on is the var_dump
function, as provided by the Xdebug extension : just install the extension (easy, both on windows and Linux), and var_dump
gets a better output :
我更喜欢的是v_dump函数,由Xdebug扩展提供:只需安装扩展(在windows和Linux上都很容易),var_dump得到更好的输出:
- better formating
- HTML
- HTML
- colors
- 颜色
- 更好的使格式化HTML的颜色
- and you have options to tune how much informations should be displayed
- 你可以选择调整显示多少信息
And a quick screenshot :
还有一个快速的截图:
And, of course, Xdebug brings loads of other usefull stuff, like remote debugging (i.e. graphical debugging of your PHP application, in Eclipse PDT for instance), profiling, ...
当然,Xdebug会带来很多其他有用的东西,比如远程调试(例如,在Eclipse PDT中对PHP应用程序进行图形化调试)、分析……
#3
33
我自己写了:REF (demo):
Plans are to add text-only rendering, and display info about the input expression like Kint does...
计划是添加纯文本渲染,并显示有关输入表达式的信息,如Kint……
#4
24
Here's mine, which I use inline, very useful:
这是我的,我使用内联,非常有用:
$pretty = function($v='',$c=" ",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'<NULL>':"<strong>$v</strong>");}return$r;};
echo $pretty($some_variable);
#5
16
You are looking for Krumo (Warning, Chrome alerts for Malware).
您正在寻找Krumo(警告,恶意软件的Chrome警告)。
To put it simply, Krumo is a replacement for print_r() and var_dump(). By definition Krumo is a debugging tool (initially for PHP4/PHP5, now for PHP5 only), which displays structured information about any PHP variable.
简单地说,Krumo是print_r()和var_dump()的替代品。根据定义,Krumo是一个调试工具(最初用于PHP4/PHP5,现在只用于PHP5),它显示关于任何PHP变量的结构化信息。
#6
9
我喜欢Firephp + firebug
- It writes the logging information out using headers, so it doesn't break AJAX.
- 它使用头文件来写日志信息,所以它不会破坏AJAX。
- Gives you a very nice graphical representation of the variables/objects you log
- 为您提供了一个非常好的您所记录的变量/对象的图形表示
- Can display file name and line number where each log statement occurs
- 是否可以在出现每个日志语句的地方显示文件名和行号
- Easy to use in your project, either with a procedural or object-oriented API
- 易于在项目中使用,无论是使用过程API还是面向对象API
#7
8
My (partial) solution for this is the simply add a function like this (using Google Chrome):
我的(部分)解决方案是简单地添加这样的函数(使用谷歌Chrome):
<?
function console_dump($value)
{
?>
<script>
console.log(<? echo json_encode($value); ?>);
</script>
<?
}
?>
Press Ctrl + Shift + J (opens up the console), and you can find there the JSON structure. Even more useful for a pretty print of JSON responses ofcourse.
按Ctrl + Shift + J(打开控制台),您可以在那里找到JSON结构。当然,对于漂亮打印JSON响应更有用。
#8
7
I've been using dBug, which emulates Coldfusion's awesome cfdump
tag:
我一直在使用dBug,它模仿Coldfusion超棒的cfdump标签:
http://dbug.ospinto.com/examples.php
http://dbug.ospinto.com/examples.php
#9
7
A complete example of what I use ...
我用的一个完整的例子……
<pre>
<?php
//*********** Set up some sample data
$obj = new stdClass;
$obj->a=123;
$obj->pl=44;
$obj->l=array(31,32);
$options = array(
'Orchestra'=>array(1=>'Strings', 8=>'Brass', 9=>$obj, 3=>'Woodwind', 16=>'Percussion'),
2=>'Car',
4=>'Bus',
'TV'=>array(21=>'Only Fools', 215=>'Brass Eye', 23=>'Vic Bob',44=>null, 89=>false));
//*********** Define the function
function dump($data, $indent=0) {
$retval = '';
$prefix=\str_repeat(' | ', $indent);
if (\is_numeric($data)) $retval.= "Number: $data";
elseif (\is_string($data)) $retval.= "String: '$data'";
elseif (\is_null($data)) $retval.= "NULL";
elseif ($data===true) $retval.= "TRUE";
elseif ($data===false) $retval.= "FALSE";
elseif (is_array($data)) {
$retval.= "Array (".count($data).')';
$indent++;
foreach($data AS $key => $value) {
$retval.= "\n$prefix [$key] = ";
$retval.= dump($value, $indent);
}
}
elseif (is_object($data)) {
$retval.= "Object (".get_class($data).")";
$indent++;
foreach($data AS $key => $value) {
$retval.= "\n$prefix $key -> ";
$retval.= dump($value, $indent);
}
}
return $retval;
}
//*********** Dump the data
echo dump($options);
?>
</pre>
Outputs ...
输出……
Array (4)
[Orchestra] = Array (5)
| [1] = String: 'Strings'
| [8] = String: 'Brass'
| [9] = Object (stdClass)
| | a -> Number: 123
| | pl -> Number: 44
| | l -> Array (2)
| | | [0] = Number: 31
| | | [1] = Number: 32
| [3] = String: 'Woodwind'
| [16] = String: 'Percussion'
[2] = String: 'Car'
[4] = String: 'Bus'
[TV] = Array (5)
| [21] = String: 'Only Fools'
| [215] = String: 'Brass Eye'
| [23] = String: 'Vic Bob'
| [44] = NULL
| [89] = FALSE
#10
6
Here is mine:
这是我的:
public function varToHtml($var='', $key='') {
$type = gettype($var);
$result = '';
if (in_array($type, array('object','array'))) {
$result .= '
<table class="debug-table">
<tr>
<td class="debug-key-cell"><b>'.$key.'</b><br/>Type: '.$type.'<br/>Length: '.count($var).'</td>
<td class="debug-value-cell">';
foreach ($var as $akey => $val) {
$result .= sbwDebug::varToHtml($val, $akey);
}
$result .= '</td></tr></table>';
} else {
$result .= '<div class="debug-item"><span class="debug-label">'.$key.' ('.$type.'): </span><span class="debug-value">'.$var.'</span></div>';
}
return $result;
}
Styled with:
风格:
table.debug-table {
padding: 0;
margin: 0;
font-family: arial,tahoma,helvetica,sans-serif;
font-size: 11px;
}
td.debug-key-cell {
vertical-align: top;
padding: 3px;
border: 1px solid #AAAAAA;
}
td.debug-value-cell {
vertical-align: top;
padding: 3px;
border: 1px solid #AAAAAA;
}
div.debug-item {
border-bottom: 1px dotted #AAAAAA;
}
span.debug-label {
font-weight: bold;
}
#11
5
I recently developed a free chrome extension (work in progress) in order to beautify my var dumps with no libraries, no pre tags and no installation to each and every app. All done with JavaScript and regEx. All you have to do is install the extension and your good to go. I am working on a Firefox version as well. Here is the GitHub page. I hope to have it available on the chrome and firefox webstores soon!
我最近开发了一个免费的chrome扩展(正在开发中),以美化我的var转储,没有库、没有前置标签,也没有安装每个应用程序。你所要做的就是安装扩展,然后你就可以离开了。我也正在开发一个Firefox版本。这是GitHub的页面。我希望它能很快在chrome和火狐网络商店上使用!
https://github.com/alexnaspo/var_dumpling
https://github.com/alexnaspo/var_dumpling
Here is an example output:
这里有一个输出示例:
#12
#13
1
Those fancy libraries are great ... except the overhead. If you want a simple, pretty var_dump that takes infinite parameters, try my function. It adds some simple HTML. Data attributes are added too, if you use HTML5, lower versions will just ignore them, but makes it easy to open element in browser console and get a little more info if what you see on screen is not enough.
那些漂亮的图书馆很棒……除了开销。如果您想要一个简单的、漂亮的、具有无限参数的var_dump,请尝试我的函数。它添加了一些简单的HTML。数据属性也被添加,如果你使用HTML5,低级版本会忽略它们,但是如果你在屏幕上看到的还不够的话,打开浏览器控制台的元素并获得更多的信息是很容易的。
The layout is very simple, no overhead. Provides a ton of info for each parameter including things like gettype
and even class
name for Object dumps (including XML). It's tried and true, I've been using it for years.
布局非常简单,没有开销。为每个参数提供大量信息,包括gettype,甚至对象转储的类名(包括XML)。这是事实,我已经用了很多年了。
function preDump() { // use string "noEcho" to just get a string return only
$args = func_get_args();
$doEcho = TRUE; $sb;
if ($args) {
$sb = '<div style="margin: 1em 0;"><fieldset style="display:inline-block;padding:0em 3em 1em 1em;"><legend><b>preDump: '.count($args).' Parameters Found.</b></legend>';
foreach (func_get_args() as $arg) {
if (gettype($arg) == 'string') if ($arg == 'noEcho') { $doEcho = FALSE; $sb = preg_replace('/(preDump: )[0-9]+/', 'preDump: '.(count($args)-1), $sb); continue; }
$sb .= '<pre data-type="'.gettype($arg).'"';
switch (gettype($arg)) {
case "boolean":
case "integer":
$sb .= ' data-dump="json_encode"><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')</b></p><p>';
$sb .= json_encode($arg);
break;
case "string":
$sb .= ' data-dump="echo"><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')</b></p><p>';
$sb .= $arg;
break;
default:
$sb .= ' data-dump="var_dump"';
if (is_object($arg)) $sb .= 'data-class="'.get_class($arg).'"';
$sb .= '><p style="border-bottom:1px solid;margin:0;padding:0 0 0 1em;"><b>gettype('.gettype($arg).')';
if (is_object($arg)) $sb .= ' ['.get_class($arg).']';
$sb .= '</b></p><p>';
ob_start();
var_dump($arg);
$sb .= ob_get_clean();
if (ob_get_length()) ob_end_clean();
}
$sb .= '</p></pre>';
}
$sb .= '</fieldset></div>';
}
else {
$sb = '<div style="margin: 1em 0;"><fieldset style="display:inline-block;"><legend><b>preDump: [ERROR]</b></legend><h3>No Parameters Found</h3></fieldset></div>';
}
if ($doEcho) echo($sb);
return $sb;
}
And If you use Codeigniter, add it too your CI EXTREMELY SIMPLY. First, go to application/config/autoload.php
and make sure the helper
'string'
is on.
如果你使用Codeigniter,添加它也非常简单。首先,去应用程序/配置/自动装载。php,并确保助手“字符串”是打开的。
$autoload['helper'] = array( 'string' );
Then simply go create a file named MY_string_helper.php
in application/helpers
and simple insert the function in a typical if
statement for existence check.
然后创建一个名为MY_string_helper的文件。php在应用程序/助手和简单插入函数在一个典型的if语句中进行存在检查。
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
if (!function_exists('preDump')) {
function preDump() {
...
}
}
// DON'T CLOSE PHP
|OR|, if you want to take it a different direction.
|或者|,如果你想换个方向。
The following snippet is the same as above, except will show your variables in the browser console. This can sometimes make it easier to debug sql object calls and other array and object calls where you're missing the key name or whatever.
下面的代码片段与上面的代码片段相同,只是将在浏览器控制台显示变量。这有时可以使调试sql对象调用和其他数组和对象调用更容易,在这些调用中您将丢失键名或其他名称。
function consoleDump() { // use string "noEcho" to just get a string return only
$args = func_get_args();
$doEcho = TRUE; $sb;
if ($args) {
$sb = '<script type="text/javascript">console.log("<" + new Array('.(count($args) < 10 ? '49': '48').').join("-") + "[consoleDump: '.count($args).' items]" + new Array(50).join("-") + ">"); console.log([';
foreach (func_get_args() as $i => $arg) {
if (gettype($arg) == 'string') if ($arg == 'noEcho') { $doEcho = FALSE; $sb = preg_replace('/(consoleDump: )[0-9]+/', 'consoleDump: '.(count($args)-1), $sb); continue; }
$sb .= '{ "type": "'.gettype($arg).'", ';
switch (gettype($arg)) {
case "boolean":
case "integer":
case "string":
$sb .= '"value": '.json_encode($arg);
break;
default:
$sb .= '"value": '.json_encode($arg);
if (is_object($arg) || is_array($arg)) $sb .= ', "count": '.json_encode(count((array)$arg));
if (is_object($arg)) $sb .= ', "objectClass": "'.get_class($arg).'"';
}
$sb .= '}';
if ($i < count($args)-1) $sb .= ', ';
}
$sb .= ']); console.log("<" + new Array(120).join("-") + ">"); </script>';
}
else {
$sb = '<script type="text/javascript">console.log("<" + new Array(120).join("-") + ">");console.log("consoleDump: [ERROR] No Parameters Found");console.log("<" + new Array(120).join("-") + ">");</script>';
}
if ($doEcho) echo($sb);
return $sb;
}
Works with everything!
适用于一切!
consoleDump($simpXMLvar, $_SESSION, TRUE, NULL, array( 'one' => 'bob', 'two' => 'bill' ), (object)array( 'one' => 'bob', 'two' => 'bill' ));
<------------------------------------------------[consoleDump: 6 items]------------------------------------------------->
[Object, Object, Object, Object, Object, Object]
// This drops down to show your variables in JS objects, like:
0: Object
count: 4
objectClass: "SimpleXMLElement"
type: "object"
value: Object
__proto__: Object
// ...etc...
<----------------------------------------------------------------------------------------------------------------------->
#14
1
To make the list more complete - Symfony developers released a usable-as-standalone dumper alternative:
为了使列表更完整,Symfony开发人员发布了一个可用的作为独立的翻斗车替代品:
https://github.com/symfony/var-dumper
https://github.com/symfony/var-dumper
You can read about it more here:
你可以在这里读到更多:
http://www.sitepoint.com/var_dump-introducing-symfony-vardumper/
http://www.sitepoint.com/var_dump-introducing-symfony-vardumper/
#15
0
I wrote small class that is similar to Krumo, but much easier to embed to app.
我写了一个类似Krumo的小类,但是更容易嵌入到app中。
Here is link: https://github.com/langpavel/PhpSkelet/blob/master/Classes/Debug.php
这是链接:https://github.com/langpavel/PhpSkelet/blob/master/Classes/Debug.php
And here sample output: http://langpavel.php5.cz/debug_sample.html
这里是示例输出:http://langpavel.php5.cz/debug_sample.html
#16
0
PHP Array Beautifier This simple tool takes an array or object output in PHP, such as a print_r() statement and formats it in color coding to easily read your data. http://phillihp.com/toolz/php-array-beautifier/
这个简单的工具使用PHP中的数组或对象输出,例如print_r()语句,并将其格式化为彩色代码,以便轻松读取数据。http://phillihp.com/toolz/php-array-beautifier/
#17
0
Yet another home-grown version:
另一个本土版:
http://github.com/perchten/neat_html
http://github.com/perchten/neat_html
I like to think it's pretty flexible. It doesn't aim for particular output environment but has a bunch of optional arguments you can specify why change the output/print or behaviour, as well as some persistent settings.
我认为它很灵活。它不针对特定的输出环境,但是有许多可选参数,您可以指定为什么要更改输出/打印或行为,以及一些持久设置。
#18
0
Here is a chrome extension that I wrote to solve this problem.
这是我为解决这个问题而编写的chrome扩展。
https://chrome.google.com/webstore/detail/varmasterpiece/chfhddogiigmfpkcmgfpolalagdcamkl
https://chrome.google.com/webstore/detail/varmasterpiece/chfhddogiigmfpkcmgfpolalagdcamkl
#19
0
I developed a chrome extension and jquery plugin in order to beautify var_dumps
我开发了一个chrome扩展和jquery插件来美化var_dumps
https://github.com/netfox01/fleX-debug
https://github.com/netfox01/fleX-debug
#20
0
My preferred is debug from https://github.com/hazardland/debug.php which is library with containing only single function named as debug (You can just copy that function in your project or in your library). Typical debug() html output looks like this:
我更喜欢使用https://github.com/gifland/debug.php进行调试,它是一个只包含一个名为debug的函数的库(您可以在项目或库中复制该函数)。典型的debug() html输出如下所示:
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):
但是,您可以将数据作为具有相同功能的纯文本(有4个空格缩进的选项卡)输出(如果需要,甚至可以在文件中记录):
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"
#21
0
If you're dealing with very big arrays in PHP, this function may help:
如果在PHP中处理非常大的数组,这个函数可能会有所帮助:
function recursive_print ($varname, $varval) {
if (! is_array($varval)):
print $varname . ' = ' . var_export($varval, true) . ";<br>\n";
else:
print $varname . " = array();<br>\n";
foreach ($varval as $key => $val):
recursive_print ($varname . "[" . var_export($key, true) . "]", $val);
endforeach;
endif;
}
It basically dumps the whole array where each element is in separate line, which is beneficial to find the right full paths for certain elements.
它基本上转储整个数组,其中每个元素都在单独的行中,这有利于为某些元素找到正确的完整路径。
Example output:
示例输出:
$a = array();
$a[0] = 1;
$a[1] = 2;
$a[2] = array();
$a[2][0] = 'a';
$a[2][1] = 'b';
$a[2][2] = 'c';
See: How to export PHP array where each key-value pair is in separate line?
参见:如何导出每个键值对在单独一行中的PHP数组?
#22
0
I'm surprised nobody mentioned the easiest (albeit not very pretty) code. If you just want to get a readable output (no colors or indentation), a simple <pre>
around a var_dump
works, as in:
我很惊讶没有人提到最简单(虽然不是很漂亮)的代码。如果您只想获得一个可读的输出(没有颜色或缩进),那么在var_dump前后使用一个简单的
就可以了,如下所示:
echo "<pre>";
var_dump($myvariable);
echo "</pre>";
Can't get much lower overhead than this!
没有比这更低的开销了!
#23
-1
TVarDumper
This is a great tool which is intended to replace the buggy PHP function var_dump
and print_r
, since it can correctly identify the recursively referenced objects in a complex object structure. It also has a recursive depth control to avoid indefinite recursive display of some peculiar variables.
这是一个很好的工具,用于替换有bug的PHP函数var_dump和print_r,因为它可以在复杂的对象结构中正确地标识递归引用的对象。它还具有递归深度控制,以避免某些特殊变量的无限递归显示。
See: TVarDumper.php
.
看到:TVarDumper.php。
For other alternative solutions which provides more advantages over var_dump
and print_r
and can support circular references, please check: Using print_r and var_dump with circular reference.
对于其他替代解决方案,它们比var_dump和print_r具有更大的优势,并且可以支持循环引用,请检查:使用print_r和var_dump并使用循环引用。
For more ideas, check also: How do you debug PHP scripts?
要了解更多的想法,还可以检查:如何调试PHP脚本?