2010-08-08 138 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