2014-09-12 39 views
1

第一要素+属性和一个XML文件的副元素+属性其实我想我的网页上阅读PHP5这个XML文件。阅读PHP5

我有这样的例子作为我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 | ??--- [阵列这里结果] ---

但我需要这个页面作为数组就是这样的阅读产品名称:

名称|金额|产品

面条| 5 | pasta1,pasta2

肉类| 18 | meat1,meat2

请,任何信息将是有益的!

+1

这应该使用更容易'SimpleXMLElement' – Ghost 2014-09-12 13:51:09

+0

我怎样才能使用的SimpleXMLElement读取与它们的属性,第一和第二要素是什么?并感谢您的回答! – user3050478 2014-09-12 13:55:16

回答

1

其实我挺有用的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>'; 

一旦寻找到手动,你需要将它扩大到拿到样品,环路的childNodes(这是产品),并再次使用->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>'; 
+0

哦,我的天啊!非常感谢!!!它真的起作用了!我真的很感激它,现在我可以研究你的代码:)谢谢 – user3050478 2014-09-12 14:02:44

+0

@ user3050478肯定没有问题!很高兴它有帮助! – Ghost 2014-09-12 14:06:43