ASCII Tables PHP Class
August 20th, 2007 • General
The following mess that I’ll call code is a rough translation from a Python implementation, found on Reddit. Somebody beat me to a Ruby version, so I decided to flex those rusty PHP braincells.
Please forgive running lines, lack of refactoring and some stupid practices. Don’t blame PHP, because this can be refactored to a more concise version. But like I said, this is a translation, not a reimplementation.
Here’s how to use it:
<?php
$table <<<EOP
---------------------------
| | | |
| | | |
| | | |
| |-------| |
| | | |
| | |-------|
| | | |
| | | |
|---------| |-------|
| | | | |
| | |-------| |
| | | | |
| | | | |
| | | | |
---------------------------
EOP;
$asciiTable = new AsciiTable($table);
echo $asciiTable->toHTML();
?>
And here’s the code:
#!/usr/bin/php <?php class AsciiTable { function AsciiTable($table) { // $this->grid is an array. $this->grid[$y] is a string, // this explains count vs. strlen below. } function toHTML() { $this->parseAsciiTable(); return $this->renderHtml(); } function parseAsciiTable() { $grid = $this->grid; { { && $grid[$y+1][$x] == '|' && $grid[$y][$x+1] == '-' ) { // We can't do an array_pos with a callback. Darn. { if ( $grid[$bottom+1][$x+1] == '-' ) break; } $this->y_delimiters[] = $bottom; $this->x_delimiters[] = $right; 'r' => $right, 'b' => $bottom)); } } } $this->boxes = $boxes; return $boxes; } function rowSpans() { foreach ( $this->y_delimiters as $delim ) { foreach ( $this->boxes as $index => $box ) { if ( $box['y'] < $delim && $box['b'] >= $delim ) { $this->boxes[$index]['rs']++; } } } } function colSpans() { foreach ( $this->x_delimiters as $delim ) { foreach ( $this->boxes as $index => $box ) { if ( $box['x'] < $delim && $box['r'] >= $delim ) { $this->boxes[$index]['cs']++; } } } } function renderHtml() { $this->rowSpans(); $this->colSpans(); $boxes_left = $this->boxes; foreach ( $this->y_delimiters as $delim ) { foreach ( $boxes_left as $index => $box ) { if ( $box['y'] < $delim ) { $boxes_in_row[] = $box; } } // sory by $box['x'] == $b["x"]) ? 0 : ($a["x"] < $b["x"]) ? -1 : 1;')); $rows[] = $boxes_in_row; } $table = "<table border=\"border\">\n"; foreach ( $rows as $row ) { $table .= " <tr>\n"; foreach ( $row as $box ) { <td rowspan=\"%d\" colspan=\"%d\">%s</td>\n", $box['rs'], $box['cs'], ); } $table .= " </tr>\n"; } $table .= "</table>\n"; return $table; } } ?>