简单XML - 如何选择具有特定属性值的所有元素

时间:2010-08-08 14:01:53

标签: php xml

用户可以选择性能,因此性能元素具有唯一ID。我想基本上说:

选择所有预订 - >预订['座位'] FROM performance-> performance ['id = 2']。

希望这很有道理,我真的很难选择简单的XML。

先谢谢你,亨利。

    <performances>
                <performance id="7" time="12:00" day="Monday" month="June" year="2010">
                    <reservations>
                        <reservation seat="a7"/>
                        <reservation seat="a2"/>
                        <reservation seat="a3"/>
                    </reservations>
                </performance>
                <performance id="8" time="12:00" day="Tuesday" month="June" year="2010">
                    <reservations>
                        <reservation seat="a8"/>
                    </reservations>
                </performance>
</performances>

额外信息:

我目前正在使用:echo $xml2->show->performances->performance['0']->reservations->reservation['seat']

这可以从第一次演出中得到一个预订,但我希望所有来自演出的预订都是id为'3'。

2 个答案:

答案 0 :(得分:2)

你的“SQL”:

SELECT reservations->reservation['seat'] FROM performances->performance['id=2']

可以重新表述为:

FROM performances->performance['id=2'] SELECT reservations->reservation['seat'] 

可以重新表述为XPath:

//performances/performance[@id=2]/reservations/reservation/@seat

Ant就是你所需要的。请看SimpleXML's xpath() method

答案 1 :(得分:1)

<?php
// create a variable repsresenting the xml to parse through
$string = '<performances>
            <performance id="7" time="12:00" day="Monday" month="June" year="2010">
                <reservations>
                    <reservation seat="a7"/>
                    <reservation seat="a2"/>
                    <reservation seat="a3"/>
                </reservations>
            </performance>
            <performance id="8" time="12:00" day="Tuesday" month="June" year="2010">
                <reservations>
                    <reservation seat="a8"/>
                </reservations>
            </performance>
</performances>';

// create a variable representing a SimpleXMLElement instance
$xml = simplexml_load_string($string);

// create a variable representing the desired results, using the xpath method for
// the SimpleXMLElement instance previously created.
$results = $xml->xpath('//performances/performance[@id=2]/reservations/reservation/@seat');

?>

很抱歉在这里偷走Tomalak的雷声。有些人有时需要拼写出来。