user754730 user754730 - 1 year ago 98
PHP Question

PHP parse XML file with grouping

I have the following xml code from a library source:

<?xml version="1.0" encoding="UTF-8"?>
<Column Collections="Books.ID">
<Column Collections="Books.InStock">
<Column Collections="Books.HowMany">

How can I put that data into a html table with SimpleXML?

Answer Source

Personally, I would use DOMDocument over SimpleXML, as it's easier to use without all the magic. But effectively they can both do the same thing to meet your needs here.

What you're trying to do is take all of the Column nodes to get their column names (i.e. the Collections attribute) and put them in a list.

Then you need to get all the rows of the table by building a transposed matrix of the Row nodes from their respective Column parent nodes.

Here's a simple example of how to do that.

$dom = new DOMDocument;
$dom->load($xmlFileName); // load the XML into the DOM

// get all column names
$columnNames = [];
$columns = $dom->getElementsByTagName('Column');
foreach($columns as $column) {
  $columnNames[] = $column->getAttribute("Collections");

// get all rows by column [i.e. cells]
$rows = [];
foreach($columns as $c => $column) {
  foreach($column->getElementsByTagName('Row') as $r => $row) {
    $rows[$r][$c] = $row->nodeValue;

Printing out the HTML

Now you can just print out the HTML table like this.

// print out the HTML table
echo "<table>";

echo "<thead>";
echo "<tr>";
foreach($columnNames as $columnName) { // the thead
  echo "<th>$columnName</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
foreach($rows as $row) { // the tbody
  echo "<tr>";
  foreach($row as $column) {
    echo "<td>$column</td>";
  echo "</tr>";
echo "</tbody>";

echo "</table>";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download