Php 具有特殊条件的xml解析循环

Php 具有特殊条件的xml解析循环,php,simplexml,Php,Simplexml,我想使用SimpleHP循环遍历一个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->expor

我想使用SimpleHP循环遍历一个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 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>
如果您注意到xml中的一些统计数据之间有一行

<New_Line />


当我遇到这样的情况时,我想回显一些破折号,但我不确定您是如何做到的,因为我不熟悉simplexml,可以说这在XML中是一个糟糕的结构选择,因为实际上可能意味着有多组
s,因此,应该有一些父对象来代表每个单独的组。尽管如此,使用SimpleXML还是非常简单

诀窍是按顺序迭代所有子节点,而不管它们的名称如何。然后在这个循环中,你可以决定如何行动

这里有一个例子(和);请注意,我添加了
->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;
    }
}
foreach($xml->config->exported->items->children()作为$node)
{
开关($node->getName())
{
案例“项目”:
$item_name=(字符串)$node['name'];
回显“项目名称:.$item_name.”
; 打破 “新线路”案例: 回声“
”; 打破 } }
<New_Line />
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;
    }
}