Dynamic table creation with PHP 5

This is a very simple and effective solution for building dynamic tables.

// Create an XML object starting with the table tags
$table = new SimpleXMLElement('<table></table>');

// Add attributes to the table tag.  Here we are adding a class.
$table->addAttribute('class','table table-data');

// Add the header row
$table_row = $table->addChild('tr');

// Add a class to the header
$table_row->addAttribute('class','table-header');

// Loop through the array and build the headers based on the array keys
foreach(array_keys($data[0]) as $head){
$row_col = $table_row->addChild('th', $head);
}

// Loop through each row in the data
foreach($data as $row){
$table_row = $table->addChild('tr');

// Loop through each column
foreach($row as $col){
$row_col = $table_row->addChild('td', $col);
}
}

// Print the HTML table on the page.  This could also be returned in a function.
echo $table->asXML();

Comments

Hi there, I dont know if I am writing in a proper board but I have got a problem with activation, link i receive in email is not working... http://ekindesigns.com/?0152f25761f442372c864ff4b36,

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <img>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Twitter-style @usersnames are linked to their Twitter account pages.

More information about formatting options