Jump to content

how to print tab delimited tables :s ?


scod

Recommended Posts

hello all!

 

well, i want to print in a text file, a table like the ones that appears in mysql's console, something like this,..

 

+------+----------+------+
| id   | order_no | name |
+------+----------+------+
|    1 |       20 | bxxx |
|    2 |     NULL | bbbb |
|    3 |     NULL | cccc |
+------+----------+------+

 

 

yep, I can do a tab delimited adding a '\t' after each record, but if the record its too long, the structure of the table just gets ugly :P

 

anyone knows a class, function or way to do it without losing the presentation of the table?

 

thank's  :)

 

 

Link to comment
https://forums.phpfreaks.com/topic/109208-how-to-print-tab-delimited-tables-s/
Share on other sites

It will take some programming. Actually sounds like a fun project, but what you need to do is the following:

 

Get the largest string for each column and ensure you extend the column (using +---+ ) to that size.

 

Optionally, you could set a total length for the entire table (90 chars for standard terminal please :)) and /or set a cutoff length to add a newline.

It will take some programming. Actually sounds like a fun project, but what you need to do is the following:

 

Get the largest string for each column and ensure you extend the column (using +---+ ) to that size.

 

Optionally, you could set a total length for the entire table (90 chars for standard terminal please :)) and /or set a cutoff length to add a newline.

 

yep, actually I'm working in the function, but I'm takin so long, thanks for the tips

 

c ya  :)

 

and thanks again

try

<?php
$data = array(
array('id' => 1, 'order_no' => 20, 'name' => 'bxxx'),
array('id' => 2, 'order_no' => 'NULL', 'name' => 'bbbbbbb'),
array('id' => 3, 'order_no' => 'NULL', 'name' => 'cccc')
);
foreach ($data[0] as $k => $v) $max_len[$k] = strlen($k);
foreach ($data as $d){
foreach ($d as $k => $v){
	if ($max_len[$k] < strlen("$v")) $max_len[$k] = strlen("$v");
}
}
$table = '';
foreach ($max_len as $i) $table .= '+-'.str_repeat('-', $i); $table .= "+\n";
foreach ($max_len as $n => $i) $table .= '| '.str_pad($n, $i, ' ',0); $table .= "|\n";
foreach ($max_len as $i) $table .= '+-'.str_repeat('-', $i); $table .= "+\n";
foreach ($data as $d){
foreach ($d as $k => $v){
	$table .= '| '. str_pad($v, $max_len[$k], ' ', 0); 
}
$table .= "|\n";
}
foreach ($max_len as $i) $table .= '+-'.str_repeat('-', $i); $table .= "+\n";
echo $table;
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.