Html Table Generating Class (HtmlTable.php)
May 5th, 2009 by Steven Lloyd Watkin
I required to generate a HTML table from PHP data for a project that I was working on. Unfortunately after a bit of Googling I couldn’t really find anything that was suitable so I decided to create my own.
I realise that this may not be the best table generating class ever and there’s probably a few bugs still in it, but I’d prefer to share and if anyone wants a better version I’ll look into it
I originally wanted to create a table built up of seperate objects e.g. cell object, row object (built up of cell objects), but I realised the overhead on this would be HUGE! So I’ve gone back to an array setup.
The class will calculate the maximum number of columns used in the header, footer, or body and write out that number of columns. Headers, Footers, and the Caption are optional. Attributes are made up of an array where the key is the attribute name and the value is the attribute value. Attributes are applied to table tag (on table creation – class initialisation), table rows (array[row][attribute]), and table cells (array[row][column][attribute]) this applies for headers, footers, and the table body.
Example
I always find the best way to look at something is to use an example so here we go:
$table = new HtmlTable(array('class' => 'sortable', 'style' => 'width: 550px;'));
$header[0][0]['content'] = ‘ID’;
$header[0][1]['content'] = ‘Title’;
$header[0][2]['content'] = ‘Date’;
$header[0][3]['content'] = ‘Site’;
$table->addHeader($header);
$i = 0;
foreach ($newsList AS $newsItem) {
$itemLink = “{$newsItem['title']}”;
$tableBody[$i] = array(0 => array(’content’ => $newsItem['id'],
‘attributes’ => array(’style’ => ‘font-weight: bold;’
),
1 => array(’content’ => $itemLink),
2 => array(’content’ => $newsItem['date_posted']),
3 => array(’content’ => $newsItem['site']) );
$i++;
}
$table->addBody($tableBody);
echo $table->drawTable();
| ID | Title | Date | Site |
|---|---|---|---|
| 9 | News 1 | 2009-04-04 10:40:00 | site name |
| 10 | News 2 | 2009-04-04 12:44:11 | site name |
And the HTML looks like this:
<table class = "sortable" style = "width: 550px;" > <thead> <tr > <th >ID</th>
<th >Title</th> <th >Date</th> <th >Site</th> </tr> </thead> <tbody> <tr > <td style = "font-weight: bold;" >9</td>
<td >News 1</td> <td >2009-04-04 10:40:00</td> <td >site name</td> </tr> <tr > <td style = "font-weight: bold;" >10</td> <td >News 2</td>
<td >2009-04-04 12:40:00</td> <td >site name</td> </tr>
</tbody> </table>
Code
HtmlTable.php
If you have any comments please make them below, it would be great to hear some. If you end up using it also let me know and I’ll extend it in the future 





