Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

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

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');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...