Reputation: 11
I'm trying to loop through an XML file formatted like so:
<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>
I want to echo the id
attribute of each set
in a settype
, where the settype
's type
attribute is 'hr'
This is what I've got so far, but I'm not sure what to do with the $hr array in order to echo the ids
$hr = $xml->xpath('//sets/settype[@type="hr"]/set');
Upvotes: 0
Views: 87
Reputation: 76395
You're nearly there. The SimpleXMLElement
class doesn't really offer any methods to access a specific attribute, or get at its value. What it does do is implement the Taversable
interface, and it supports array access. The class documentation is well worth a look, especially the user contributions under SimpleXMLElement::attributes
, which actually tell you how you can echo the ID's you're after.
Basically, you can keep everything you have so far (including the $hr = $xml->xpath();
). After that, it's a simple matter of iterating over the SimpleXMLElement
instances in $hr
, and doing this:
foreach ($hr as $set) {//set is a SimpleMLElement instance
echo 'ID is: ', (string) $set['id'];
}
As you can see, the attributes are accessible as array indexes, and are SimpleXMLElements
, too (so you need to cast them to a string to generate the output you want).
Upvotes: 1