¿Hay una impresión bonita para PHP?
Estoy arreglando algunos scripts PHP y me falta la bonita impresora de Ruby. es decir,
require 'pp'
arr = {:one => 1}
pp arr
Mostrará {:one => 1}. Esto incluso funciona con objetos bastante complejos y hace que excavar en un script desconocido sea mucho más fácil. ¿Hay alguna manera de duplicar esta funcionalidad en PHP?
30 answers
Ambos print_r()
y var_dump()
generará representaciones visuales de objetos dentro de PHP.
$arr = array('one' => 1);
print_r($arr);
var_dump($arr);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-22 20:54:32
Esto es lo que uso para imprimir mis arrays:
<pre>
<?php
print_r($your_array);
?>
</pre>
La magia viene con la etiqueta pre
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-05 21:23:53
Para simplificar, print_r() y var_dump() no pueden ser superados. Si desea algo un poco más elegante o está tratando con listas grandes y/o datos profundamente anidados, Krumo le hará la vida mucho más fácil: le proporciona una pantalla colapsante/expandida con un buen formato.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-22 22:02:30
Lo mejor que he encontrado hasta ahora es esto:
echo "<pre>";
print_r($arr);
echo "</pre>";
Y si lo quieres más detallado:
echo "<pre>";
var_dump($arr);
echo "</pre>";
Agregar una etiqueta HTML <pre>
en un entorno de desarrollo web respetará las nuevas líneas \n
de la función de impresión correctamente, sin tener que agregar algo de html <br>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-02 23:15:47
Para PHP, puede aprovechar fácilmente HTML y algún código recursivo simple para hacer una bonita representación de arrays y objetos anidados.
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;
}
Esto imprimirá el array como una lista de listas HTML anidadas. HTML y su navegador se encargarán de sangrar y hacerlo legible.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-15 00:12:50
¿Qué tal print_r?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-22 20:54:01
Recuerde establecer html_errors = on
en php.ini para obtener una impresión bonita de var_dump () en combinación con xdebug.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-24 10:05:54
La mejor manera de hacer esto es
echo "<pre>".print_r($array,true)."</pre>";
Ejemplo:
$array=array("foo"=>"999","bar"=>"888","poo"=>array("x"=>"111","y"=>"222","z"=>"333"));
echo "<pre>".print_r($array,true)."</pre>";
Resultado:
Array
(
[foo] = > 999
[bar] = > 888
[poo] => Array
(
[x] = > 111
[y] = > 222
[z] = > 333
)
)
Lee más sobre print_r.
Acerca del segundo parámetro de print_r "true" de la documentación:
Cuando este parámetro es set to TRUE, print_r() devolverá el información en lugar de imprimirla.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-11 14:56:36
Esta es una pequeña función que uso todo el tiempo es útil si está depurando matrices. El parámetro title le da cierta información de depuración como qué matriz está imprimiendo. también comprueba si lo ha suministrado con una matriz válida y le permite saber si no lo hizo.
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.";
}
}
Uso básico:
//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);
Resultados:
PETS
||---------------------------------||
Array
(
[0] => cat
[1] => dog
[2] => bird
[3] => mouse
[4] => fish
[5] => gerbil
)
END PETS
||---------------------------------||
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-04 06:40:18
error_log(print_r($variable,true));
Para enviar a syslog o eventlog para windows
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-22 22:17:39
Si está haciendo más depuración, Xdebug es esencial. Por defecto reemplaza var_dump()
con su propia versión que muestra mucha más información que la predeterminada de PHP var_dump()
.
También está Zend_Debug.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-22 23:03:38
No vi que nadie mencionara hacer una "coma verdadera" con su comando print_r, y luego puede usarlo en línea con html sin pasar por todos los aros o soluciones de aspecto multi-desordenado proporcionadas.
print "session: <br><pre>".print_r($_SESSION, true)."</pre><BR>";
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-21 18:21:51
Un trazador de líneas que le dará el equivalente aproximado de "ver fuente" para ver el contenido de la matriz:
Asume php 4.3.0+:
echo nl2br(str_replace(' ', ' ', print_r($_SERVER, true)));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-05 20:55:24
Esta función funciona bastante bien siempre que establezca header('Content-type: text/plain');
antes de emitir la cadena de retorno
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;
}
?>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-12 01:51:24
Si desea una representación más agradable de cualquier variable PHP (que solo texto plano), le sugiero que pruebe nice_r(); imprime valores más información útil relevante (por ejemplo: propiedades y métodos para objetos). Descargo de responsabilidad: Yo mismo escribí esto.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-29 22:32:29
Una salida de color agradable:
Echo svar_dump(array("a","b"=>"2","c"=>array("d","e"=>array("f","g"))));
Se verá como:
Fuente:
<?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(" "," ",$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');
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-01 09:14:47
Desde que encontré esto a través de Google buscando cómo formatear json para que sea más legible para la solución de problemas.
ob_start() ; print_r( $json ); $ob_out=ob_get_contents(); ob_end_clean(); echo "\$json".str_replace( '}', "}\n", $ob_out );
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-10 08:30:15
Si su servidor se opone a que cambie los encabezados (a texto sin formato) después de que se hayan enviado algunos, o si no desea cambiar su código, simplemente "ver código" desde su navegador your su editor de texto (incluso el bloc de notas) procesará las nuevas líneas mejor que su navegador, y se convertirá en un lío desordenado:
Array ([root] = > 1 [sub1] = > Array () [sub2] = > Array () [sub3] = > Array () [sub4] = > Array ( ) ...
En una representación correctamente tabulada:
[root] => 1
[sub1] => Array
(
)
[sub2] => Array
(
)
[sub3] => Array
(
)
[sub4] => Array
(
)...
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-11 22:17:52
Si desea utilizar el resultado en otras funciones, puede obtener una expresión PHP válida como una cadena usando var_export :
$something = array(1,2,3);
$some_string = var_export($something, true);
Para muchas de las cosas que la gente está haciendo en sus preguntas, espero que hayan dedicado una función y no estén copiando pegando el registro adicional. var_export
logra una salida similar a var_dump
en estas situaciones.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-24 02:21:57
Aquí hay una versión de pp que funciona tanto para objetos como para matrices (también saqué las comas):
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-07 14:54:57
Aquí hay otro volcado simple sin toda la sobrecarga de 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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-11 02:34:20
Creo que la mejor solución para imprimir json en php es cambiar el encabezado:
header('Content-type: text/javascript');
(si hace text/json, muchos navegadores solicitarán una descarga... facebook hace texto / javascript para su protocolo gráfico por lo que no debe ser demasiado malo)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-04 06:01:45
FirePHP es un plugin de Firefox que print tiene una característica de registro muy bonita.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-09 19:18:00
<?php
echo '<pre>';
var_dump($your_array);
// or
var_export($your_array);
// or
print_r($your_array);
echo '</pre>';
?>
O Usar bibliotecas externas como REF: https://github.com/digitalnature/php-ref
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-21 16:38:07
Ampliando la respuesta de @Stephen, se agregaron algunos ajustes muy menores para fines de visualización.
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;
}
Formateará cualquier matriz multidimensional de la siguiente manera:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-29 04:23:44
Esto es lo que normalmente uso:
$x= array(1,2,3);
echo "<pre>".var_export($x,1)."</pre>";
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-24 11:05:13
Hice esta función para imprimir una matriz para depurar:
function print_a($arr) {
print '<code><pre style="text-align:left; margin:10px;">'.print_r($arr, TRUE).'</pre></code>';
}
Espero que ayude, Tziuka S.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-16 14:07:42
¿Qué tal una sola función independiente llamada debug de https://github.com/hazardland/debug.php .
Típico debug () la salida html se ve así:
Pero también puede generar datos como texto sin formato con la misma función (con 4 pestañas con sangría de espacio) de esta manera (e incluso registrarlos en el archivo si es necesario):
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"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-23 09:50:14
En PHP 5.4 se puede usar JSON_PRETTY_PRINT si se utiliza la función json_encode.
json_encode(array('one', 'two', 'three'), JSON_PRETTY_PRINT);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-07 08:45:26
Junté algunas de estas opciones en una pequeña función auxiliar en
Http://github.com/perchten/neat_html /
Puede imprimir en html, con una salida ordenada, así como jsonify la cadena, autoimpresión o retorno, etc.
Maneja archivos includes, objetos, arrays, nulls vs false y similares.
También hay algunos ayudantes globalmente accesibles (pero bien delimitados) para cuando se usa la configuración de una manera más similar al entorno
Más dinámica, argumentos opcionales basados en matrices o cadenas.
Y, sigo añadiendo a ella. Así que es compatible: D
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-13 15:20:13