2010-08-08 109 views
0

用户可以选择一个性能,以便性能元素具有唯一的ID。我想基本上说:简单XML - 如何选择具有特定属性值的所有元素

选择所有保留 - >预订['座位']从演出 - >表演['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']

这得到一个预约从第一次演出,但我想从性能上都保留有“3”例如ID 。

+0

[SimpleXML:选择具有某个属性值的元素]的可能重复(http://stackoverflow.com/questions/992450/simplexml-selecting-elements-which-have-a-certain-attribute-value) – hakre 2013-10-26 19:50:51

回答

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 

蚂蚁这就是你所需要的。看看SimpleXML's xpath() method

+0

我写了FROM演出,但我试图强调我希望它来自特定的演出ID元素。 我只使用PHP。 – Henryz 2010-08-08 14:10:53

+1

这正是XPath所做的。它仅从具有特定ID的演出中选择预约。 *(PS:什么“我只用PHP”是什么意思?)* – Tomalak 2010-08-08 14:12:08

+0

对不起,我只是非常困惑。 我需要编写一些PHP,它将从ID为7的元素性能中获取3个预留座位值。 – Henryz 2010-08-08 14:29:50

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的雷声在这里。有些人需要它有时拼写出来。

+0

Hey Cory,我对XML和XPATH都很陌生,所以我很难理解这个概念。 我不认为你会知道是否有可能使用xpath写入(addAtrribute)? – Henryz 2010-08-09 08:24:14

相关问题