在PHP5上读取XML文件的第一个元素+属性和第二个元素+特性


Read first element+attributes and secondary elements+attributes of a XML file on PHP5

实际上我想让我的页面在PHP5上读取这个XML文件。

我有一个示例作为samples.xml文件:

<sample amount="5" name="Pasta" dest="pasta/sample_pasta.lua">
    <product name="pasta1"/>
    <product name="pasta2"/>
</sample>
...
<sample amount="18" name="Meat" dest="pasta/sample_meat.lua">
    <product name="meat1"/>
    <product name="meat2"/>
</sample>

还有我的php代码:

<?php
echo '<table><tr><td>Name</td><td>Amount</td><td>Product</td></tr>';
$reader = new XMLReader();
if (!$reader->open("samples.xml")) {
die("Failed to open 'samples.xml'");
}
while($reader->read()) {
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'sample') {
$amount = $reader->getAttribute('amount');
$name = $reader->getAttribute('name');
echo '<tr><td>'.$name.'</td><td>'.$amount.'</td><td>---?[array result here]?---</td></tr>';
}
echo '</table>';
?>

这就是我的脚本打印在页面上的内容:

名称|金额|产品

意大利面|5|---?[此处为数组结果]?---

肉|18|---?[此处为数组结果]?---

但我需要这个页面将产品名称读取为数组,如下所示:

名称|金额|产品

Pasta|5|pasta1,pasta2

肉|18|肉1,肉2

请提供任何信息!!!

实际上我已经很习惯SimpleXMLElement了,但这应该会破解它。

echo '<table cellpadding="10"><tr><td>Name</td><td>Amount</td><td>Product</td></tr>';
$reader = new XMLReader();
if (!$reader->open("samples.xml")) {
die("Failed to open 'samples.xml'");
}
while($reader->read()) {
    if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'sample') {
        $amount = $reader->getAttribute('amount');
        $name = $reader->getAttribute('name');
        $sample = $reader->expand();
        $products = array();
        foreach($sample->childNodes as $product) {
            if(get_class($product) != 'DOMElement') continue;
            $products[] = (string) $product->getAttribute('name');
        }
        echo '<tr><td>'.$name.'</td><td>'.$amount.'</td><td>'.implode(', ', $products).'</td></tr>';
    }
}
echo '</table>';

查看手册后,您需要将其展开以获得示例,循环子节点(即产品),然后再次使用->getAttribute。将属性聚集在一个数组中,然后内爆它们。

这是SimpleXMLElement版本(概念完全相同):

$xml = simplexml_load_file('samples.xml');
echo '<table cellpadding="10"><tr><td>Name</td><td>Amount</td><td>Product</td></tr>';
foreach($xml->sample as $sample) {
    $name = (string) $sample->attributes()->name;
    $amount = (string) $sample->attributes()->amount;
    $products = array();
    foreach($sample->product as $product) {
        $products[] = (string) $product->attributes()->name;
    }
    $products = implode(', ', $products);
    echo "
        <tr>
            <td>$name</td>
            <td>$amount</td>
            <td>$products</td>
        </tr>
    ";
}
echo '</table>';