user754730 user754730 - 3 months ago 12
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"?>
<Data>
<MyData>
<Column Collections="Books.ID">
<Row>1534</Row>
<Row>2753</Row>
<Row>3734</Row>
<Row>4029</Row>
<Row>5242</Row>
<Row>6833</Row>
<Row>7275</Row>
<Row>8456</Row>
</Column>
<Column Collections="Books.InStock">
<Row>0</Row>
<Row>0</Row>
<Row>0</Row>
<Row>0</Row>
<Row>0</Row>
<Row>0</Row>
<Row>0</Row>
<Row>0</Row>
</Column>
<Column Collections="Books.HowMany">
<Row>12</Row>
<Row>4</Row>
<Row>19</Row>
<Row>2</Row>
<Row>0</Row>
<Row>18</Row>
<Row>52</Row>
<Row>26</Row>
<Row>32</Row>
<Row>4</Row>
</Column>
</MyData>
</Data>


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

Answer

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>";
Comments