PHP 用分组解析 XML 文件

PHP parse XML file with grouping

我有以下来自库源的 xml 代码:

<?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>

如何使用 SimpleXML 将该数据放入 html table?

就我个人而言,我会使用 DOMDocument 而不是 SimpleXML,因为它更易于使用,无需所有魔法。但实际上,他们都可以做同样的事情来满足您的需求。

您要做的是获取所有 Column 节点以获取它们的列名(即 Collections 属性)并将它们放入列表中。

然后您需要通过从各自的 Column 父节点构建 Row 节点的转置矩阵来获取 table 的所有行。

这里有一个简单的例子来说明如何做到这一点。

$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;
  }
}

正在打印 HTML

现在你可以像这样打印出 HTML table。

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