使用 XML 数据填充 HTML 表


Populate an HTML table with XML data

我想用XML文件中的数据填充一个表,并且正在考虑:

1.( 创建 XML 数据:

<menu>
  <pizza>
    <regular>
      <item name="Tomato Cheese">Tomato Cheese
        <price size="small">1</price>
        <price size="large">2</price>
        <description>A</description>
      </item>
      <item name="Onion">Onion
        <price size="small">3</price>
        <price size="large">4</price>
        <description>B</description>
      </item>
    </regular>
  </pizza>
</menu>

2.( 在 HTML 中创建表格:

<table border="1">
  <thead>
    <tr>
      <th rowspan="2">Item </th>
      <th rowspan="2">Description</th>
      <th colspan="2">Price</th>
    </tr>
    <tr>
      <th>Small</th>
      <th>Large</th>
    </tr>
  </thead>
  <tbody>
    ...

3.( 在 XPath 查询上使用 foreach 语句:

 foreach  ($xml->xpath('/menu/pizza/descendant::item') as $item)
        {
            print "<tr><td>".$item."</td>" ;
        } 

这适用于第一行,但我无法弄清楚如何填充其余列。

如果您查看 SimpleXML 的基本用法示例,您会发现访问子元素(标记(是通过使用 $child = $parent->tagName 来完成的,对于非唯一名称,您可以使用 foreach ( $parent->tagName as $child ) 。要访问属性,请使用 $tag['attributeName']

下面是一些可以在代码中使用$item执行的操作:

  • $name = $item['name'];
  • $description = $item->description;
  • foreach ( $item->price as $price ) { ... }
  • 在这个循环中,$size = $price['size']; - 这个实际上需要你稍微改变你的XML,因为你有small="small",这将很难使用;你最好使用<price size="small"><price size="large">所以一切都是一致的。

谢谢 IMsOP。
只是想跟进,因为我已经解决了这个问题。

首先,我运行了以下查询:

/* querying the XML data to return arrays containing pizza name, description, small price, large price  
$pName = $xml->xpath("/menu/pizza/regular/descendant::item");
$description = $xml->xpath('/menu/pizza/regular/descendant::item/description');
$sPrice = $xml->xpath('/menu/pizza/regular/descendant::item/price[@size="small"]');
$lPrice = $xml->xpath('/menu/pizza/regular/descendant::item/price[@size="large"]');

然后我使用循环填充了表。
如果有人感兴趣,这里有三种不同的方法:

/* using a WHILE loop */
$e = 0;
while ( $e < count($pName) )
{
  echo "<tr><th scope='row' class='vHeader'>".$pName[$e]."</th><td>".$description[$e]."</td><td>".$sPrice[$e]."</td><td>".$lPrice[$e]."</td></tr>";
  $e++;
}  
/* using a FOR loop */
for($i = 0 ;$i < count($pName); $i++)
{
  echo "<tr><th scope='row' class='vHeader'>".$pName[$i]."</th><td>".$description[$i]."</td><td>".$sPrice[$i]."</td><td>".$lPrice[$i]."</td></tr>"; 
} 
/* another way using a FOR loop */
for ( $e = 0; $e < count($pName); $e++ ) 
{   
   $name = $pName[$e] ;
   $desc = $description[$e] ;
   $sp = $sPrice[$e] ;
   $lp = $lPrice[$e] ;
   echo "<tr><th scope='row' class='vHeader'>".$name[0]."</th><td>".$desc[0]."</td><td>".$sp[0]."</td><td>".$lp[0]."</td></tr>"; }