繁体   English   中英

用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>"; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM