PHP SimpleXML根据节点属性获取子节点属性

时间:2015-03-07 15:31:57

标签: php xml xpath simplexml

我正在尝试遍历格式如下的XML文件:

<colors>
...
</colors>
<sets>
    <settype type="hr" paletteid="2" mand_m_0="0" mand_f_0="0" mand_m_1="0" mand_f_1="0">
        <set id="175" gender="M" club="0" colorable="0" selectable="0" preselectable="0">
            <part id="996" type="hr" colorable="0" index="0" colorindex="0"/>
        </set>
        ...
    </settype>
    <settype type="ch" paletteid="3" mand_m_0="1" mand_f_0="1" mand_m_1="0" mand_f_1="1">
        <set id="680" gender="F" club="0" colorable="1" selectable="1" preselectable="0">
            <part id="17" type="ch" colorable="1" index="0" colorindex="1"/>
            <part id="17" type="ls" colorable="1" index="0" colorindex="1"/>
            <part id="17" type="rs" colorable="1" index="0" colorindex="1"/>
        </set>
        ...
    </settype>
</sets>

我希望回显id中每个set的{​​{1}}属性,其中settype的{​​{1}}属性为'hr'

这是我到目前为止所得到的,但我不知道如何处理$ hr数组以回应ID

settype

1 个答案:

答案 0 :(得分:1)

你快到了。 SimpleXMLElement类并不真正提供访问特定属性或获取其值的任何方法。它所做的是实现Taversable接口,它支持数组访问。 class documentation非常值得一看,特别是SimpleXMLElement::attributes下的用户贡献,它实际上告诉您如何回显您之后的ID。

基本上,你可以保留到目前为止所拥有的一切(包括$hr = $xml->xpath();)。在那之后,迭代SimpleXMLElement中的$hr个实例并执行此操作很简单:

foreach ($hr as $set) {//set is a SimpleMLElement instance
    echo 'ID is: ', (string) $set['id'];
}

如您所见,属性可以作为数组索引访问,也是SimpleXMLElements(因此您需要将它们转换为字符串以生成所需的输出)。

Demo

相关问题