Html Table Generating Class (HtmlTable.php)

By , Tuesday 5th May 2009 9:11 pm

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.


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';

$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']) );
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;" >
	<tr >
		<th >ID</th>
		<th >Title</th>
		<th >Date</th>
		<th >Site</th>
	<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 >
		<td style = "font-weight: bold;" >10</td>
		<td >News 2</td>
		<td >2009-04-04 12:40:00</td>
		<td >site name</td>


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 :)

Panorama Theme by Themocracy

2 visitors online now
0 guests, 2 bots, 0 members
Max visitors today: 8 at 07:11 am UTC
This month: 15 at 12-11-2017 04:06 pm UTC
This year: 45 at 02-01-2017 10:28 pm UTC
All time: 130 at 28-03-2011 10:40 pm UTC