You are here: Re: pretty_print meets var_dump() ? « PHP Programming Language « IT news, forums, messages
Re: pretty_print meets var_dump() ?

Posted by Peter Fox on 12/20/05 20:33

Following on from Baron Samedi's message. . .
>I googled, but don't find anything...
>
>I have some pretty hairy arrays and when I var_dump() I get an
>unreadable mess.
>
>Surely someone has already written a function which will take a
>var_dump and structure it?

Here are some functions for arrays and objects that are a bit more than
print_r(). You /don't/ need to be using the trace functionality to get
the layout functionality.


If you find yourself with highly nested objects then the last function
(DumpObjectAsTree) is handy but needs another 300+ lines of PHP code
from me (ask if you want it) and Tigra Tree - free from
www.softcomplex.com/products/tigra_menu_tree/)








<?php
/*
Debugging etc functions
-----------------------


Setting up some tracing is simple:
TraceOn();
...
Trace(...);
...
TraceShow(); or TraceShow('../test/trace.htm');

*/


#--------------------------------------------------------
function ArrayToTable($ay,$Colour='#f0f0f0'){
# Return a HTML table with the array in it
#--------------------------------------------------------
if(count($ay)==0){
return("No elements in array<br>\n");
exit;
}

$firstrow=TRUE;
$t="<br><table bgcolor=$Colour border=1>";
foreach($ay as $k=>$a){
if($firstrow){
if(is_array($a)){
$t .= "<tr><td>Ø</td>";
foreach($a as $r=>$v){$t .= "<td><b>$r</b></td>";}
$t .= "</tr>\n";
$firstrow=FALSE;
}
}

$t .= "<tr>";
$t .= "<td><b>$k</b></td>";
if(is_array($a)){
foreach($a as $v){
if(!$v){
$v='<pre>Ø</pre>';
}else{
if(is_object($v)){
$v='<i>'.get_class($v).'</i>';
}
}
$t .= "<td>$v</td>";
}
}else{
if(!$a){
$a='Ø';
}else{
if(is_object($a)){
$a='<i><font color=blue>•'.get_class($a).'</font></i>';
}
}
$t .= "<td>$a</td>";
}
$t .= "</tr>\n";
}
$t .= '</table><br>';
return $t;
}

#--------------------------------------------------------
function KeyListing($Array){
# Tabulate the keys of an array
#--------------------------------------------------------
print(ArrayToTable(array_keys($Array),'green'));
}


#--------------------------------------------------------
function FormattedExport($Var){
# Exported object with a bit of extra formatting
# Returns a string suitable for sending to screen
# See also {DumpObjectAsTree}
#--------------------------------------------------------
ob_start();
var_export($Var);
$s=ob_get_contents();
ob_end_clean();

$s=str_replace('<','&lt;',$s);
$s=str_replace('>','&gt;',$s);



$s=str_replace('class','<b>class</b>',$s);
$s=str_replace("= \n array (\n );",'= <i>MT()</i>',$s);
$s=str_replace("= \n array (",' = <b>array</b>(',$s);

$s=str_replace("\n ","\n| ¦ | ¦ | ¦ | <font
color=red>",$s);
$s=str_replace("\n ", "\n| ¦ | ¦ | ¦ <font
color=green>",$s);
$s=str_replace("\n ", "\n| ¦ | ¦ | <font color=blue>",$s);
$s=str_replace("\n ", "\n| ¦ | ¦ <font color=black>",$s);
$s=str_replace("\n ", "\n| ¦ | <font color=red>",$s);
$s=str_replace("\n ", "\n| ¦ <font color=green>",$s);
$s=str_replace("\n ", "\n| <font color=blue>",$s);
$s=str_replace("\n","\n<font>",$s);
$s=str_replace("\n","</font>\n",$s);
$s="<pre>$s</pre>";
return $s;

}


#-------- TRACE FUNCTIONS -----------------------

#----------------------------------------------------------
function TraceOn(){
# Switch trace recording on.
# See TraceReset()
#----------------------------------------------------------
$_SESSION['TRACE']=1;
}

#----------------------------------------------------------
function TraceOff(){
# Switch trace recording off.
#----------------------------------------------------------
if($_SESSION['TRACE']==1){unset($_SESSION['TRACE']);}
}

#----------------------------------------------------------
function Trace($Label,$ToBeTraced='Ø',$HTMLsafe=TRUE,$Condition=TRUE){
# Main trace call
# Only records trace if (a) recording=on and (b) Condition is true
# {Label} is required and is a simple string that tags the report
# If ** appears in the label then insert a horiz-rule in report
# If * appears in the label then show as bold
# {ToBeTraced} can be one of three things
# * String - report string
# * Array - list array
# * Object - report object's contents
# {Condition} If this is false then don't record
#----------------------------------------------------------

// test to see if anything to do
if($Condition){
if(isset($_SESSION['TRACE'])){


// label with special flags
$lab=str_replace('**','',$Label);
if($lab!=$Label){
$t='<hr>'.$lab;
}else{
$lab=str_replace('*','',$Label);
if($lab!=$Label){
$t="<font color=green><b>$lab</b></font>";
}else{
$t="<font color=green>$lab</font>";
}
}
$lab = $t;


// list the array elements in one string
$t='';
if(is_array($ToBeTraced)){
$t .= ArrayToTable($ToBeTraced);
}else{
// dump a complete object
if(is_object($ToBeTraced)){
$ob= ''; $cb='';
$t .= $ob . FormattedExport($ToBeTraced);
}else{
// literal text
$ob= '('; $cb=')<br>';
$t .= $ToBeTraced;
}
if($HTMLsafe){
$t=str_replace('<br>','••',$t);
$t=htmlspecialchars($t);
$t=str_replace('••','<br>',$t);
}
}


$_SESSION['TRACELOG'] .= "<br>$lab ($t)";
}
}
}


#----------------------------------------------------------
function TraceReset(){
# Switch recording on AND clear the recording
#----------------------------------------------------------
TraceOn();
$_SESSION['TRACELOG']='';
}


#----------------------------------------------------------
function TraceShow($FileName=''){
# Produce report in HTML format
# Clears the recording afterwards
# Does not do anything if there is nothing to report. (So
# is OK to leave in when tracing is switched off.)
# If {FileName} is blank then print to screen
#----------------------------------------------------------

// don't do anything unless something to report
if(isset($_SESSION['TRACELOG'])){
$t=$_SESSION['TRACELOG'];
if($t){

// heading
$d=date('H:i:s');
$t="<b>~~~TRACE~~~</b>$d".$t."<br>\n";

// possibly write to file...
if($FileName){
$f=fopen($FileName,'w');
if($f){
fwrite($f,$t);
fclose($f);
}
}else{
// ... or print to screen
print($t);
}
// clear the log
$_SESSION['TRACELOG']='';
}
}
}

#----------------------------------------------------------
function TimeStampStr($Mode=0){
# Return a timestamp in pretty string.
# Default format is H:i:s
# {Mode} 1 ... j M y H:i:s
# {Mode} 2 ... j M y H:i
#----------------------------------------------------------
switch($Mode){
case 1 : $f= 'j M y H:i:s'; break;
case 2 : $f= 'j M y H:i'; break;
default : $f= 'H:i:s'; break;
}
return date($f);
}


#----------------------------------------------------------
function DumpObjectAsTree($SomeObject,$DestinationFile){
# Write the object in detail to the specified file
# This is presented in the form of an expandable tree
# See also {FormattedExport()} for simpler (in-line) version
#----------------------------------------------------------

// get PHP to report the object
ob_start();
var_export($SomeObject);
$s=ob_get_contents();
ob_end_clean();

// global tidy up and reformat
$s=str_replace("'",'"',$s);
$s=str_replace('<','&lt;',$s);
$s=str_replace('>','&gt;',$s);
$s=str_replace("array (\n );",'<i>MT()</i>',$s);
$s=str_replace('class','<b>object</b>',$s);
$s=str_replace("public $",'$',$s);
$s=str_replace("private $",'$',$s);
$s=str_replace("protected $",'$',$s);
$s=str_replace("(\n","\n",$s);
$s=str_replace("{\n","\n",$s);
$s=str_replace(";\n","\n",$s);

// put into an array format
// then step through it weeding and combining
$a=explode("\n",$s); // source
$b=array(); // destination
$continued=FALSE; // does next source get added to this one
foreach($a as $s){
$ts=trim($s);

// skip closers
if( ($ts=='}') or ($ts=='},') or ($ts==')')) { continue; }

// write to dest
if($continued){ // add to last line
$i=count($b)-1;
$b[$i]=$b[$i].' '.$ts;
$continued=FALSE;
}else{ // new line
$b[]=$s;
}

// flag if the next item is to carry on on same line
$continued = ((substr($ts,-5) == '=&gt;') or (substr($ts,-1) ==
'='));

}

// Build the menu
$mnu = new menuTree();
$mnu->headerText=TimeStampStr();
$mnu->AddIndentedList($b,2);

// write to file
$fp = fopen($DestinationFile, 'w');
if($fp){
fwrite($fp,$mnu->CompleteMenu());
fclose($fp);
}

// tidy up these potentially large items
unset($mnu);
unset($a);
unset($b);

}



?>

--
PETER FOX Not the same since the submarine business went under
peterfox@eminent.demon.co.uk.not.this.bit.no.html
2 Tees Close, Witham, Essex.
Gravity beer in Essex <http://www.eminent.demon.co.uk>

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация