PHP 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>

我想回显settype中每个setid属性,其中settypetype属性是'hr'

这就是我到目前为止得到的,但我不确定如何处理 $hr 数组以回显 ids

$hr = $xml->xpath('//sets/settype[@type="hr"]/set');

你快到了。SimpleXMLElement类实际上并没有提供任何方法来访问特定属性或获取其值。它的作用是实现Taversable接口,并支持阵列访问。类文档非常值得一看,尤其是 SimpleXMLElement::attributes 下的用户贡献,它实际上告诉您如何回显您想要的 ID。

基本上,您可以保留到目前为止拥有的所有内容(包括$hr = $xml->xpath();)。之后,只需遍历 $hr 中的 SimpleXMLElement 个实例,然后执行以下操作:

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

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

演示

最新更新