我有来自库源的以下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表?
答案 0 :(得分:1)
就我个人而言,我会使用DOMDocument
而不是SimpleXML
,因为它更容易使用而没有所有魔法。但实际上他们可以做同样的事情来满足你的需求。
您要做的是让所有Column
个节点获取其列名(即Collections
属性)并将其放入列表中。
然后,您需要通过从各自的Row
父节点构建Column
节点的转置矩阵来获取表的所有行。
这是一个如何做到这一点的简单例子。
$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表格。
// 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>";