2013-11-23 30 views
0

我想使用simplephp循环访问xml文件。xml解析具有特殊条件的循环

我的访问代码是这样的:

// get the path of the file 
$file = "xml/".$item_name . "_cfg.xml"; 

if(! $xml = simplexml_load_file($file)){ 
    echo 'unable to load XML file'; 
} else { 

$item_array = array(); 
foreach($xml->config->exported->item as $items) 
    { 
$item_name = (string) $items->attributes()->name; 
echo "item name: " . $item_name . "<br />"; 
} 

这将回声出在该XML的所有项名称的名称,因为一些数据是敏感的,但它基本上是这样的心不是实际的XML与不同的数据一样。

所以它会显示为基于下面的XML如下:

yellow 
blue 
orange 
red 
black 

这里是XML

<?xml version="1.0"?> 
<main> 
    <config> 
     <exported> 
      <items> 
       <item name="yellow"></item> 
       <item name="blue"></item> 
       <New_Line /> 
       <item name="orange"></item> 
       <item name="red"></item> 
       <New_Line /> 
       <item name="black"></item> 
      </items> 
     </exported> 
    </config> 
<main> 

都很好,但我需要显示的是:

yellow 
blue 
-------- 
orange 
red 
-------- 
black 

如果你在xml中注意到这个行之间有一些数据

<New_Line /> 

当我遇到我想呼应的几个短线,但我真的不知道你是怎么做的,因为我不太熟悉的SimpleXML

回答

1

可以说,这是结构的一个糟糕的选择中XML,因为大概实际上意味着有多个item s集合,因此它应该有一些父代来表示每个单独的组。尽管如此,使用SimpleXML你想要做的事情非常简单。

诀窍是use the ->children() method按顺序迭代所有子节点,不管名称如何。然后在该循​​环中,您可以examine the name of each node using ->getName()并决定如何行动。

下面是一个例子(和a live demo of it in action);请注意,我添加了->items以匹配您提供的示例XML,并使用较短的$node['name']而不是$node->attributes()->name

foreach($xml->config->exported->items->children() as $node) 
{ 
    switch ($node->getName()) 
    { 
     case 'item': 
      $item_name = (string)$node['name']; 
      echo "item name: " . $item_name . "<br />"; 
     break; 
     case 'New_Line': 
      echo '<hr />'; 
     break; 
    } 
}