[英]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.