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

PHP SimpleXML Getting a child node attribute based on a node attribute

我正在尝试遍历格式如下的 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 class 并没有真正提供任何方法来访问特定属性或获取其值。它所做的是实现 Taversable 接口,它支持数组访问。 class documentation 非常值得一看,尤其是 SimpleXMLElement::attributes 下的用户贡献,它实际上告诉您如何回显您想要的 ID。

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

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

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

Demo