2012-01-16 72 views
1

我有一個SimpleXML的元素,從XML類似如下:遍歷的SimpleXML元素通過通配符查詢

<Result> 
    <BlueAnswer>Blue</BlueAnswer> 
    <RedAnswer>Red</RedAnswer> 
    <YellowAnswer>Yellow</YellowAnswer> 

    <BlueQuestion>What is my favorite color?</BlueQuestion> 
    <RedQuestion>What is my favorite color?</RedQuestion> 
    <YellowQuestion>What is my favorite color?</YellowQuestion> 
</Result> 

我如何遍歷他們一個通配符,像這樣:

foreach ($response->Result->wildcard('*Answer') as $answer) { 
    echo "Answer: " . $answer; 
} 

這似乎很簡單,但我似乎無法弄清楚。感謝您提前提供任何幫助。

+0

你可能正在尋找的是[Xpath](http://www.php.net/manual/en/simplexmlelement.xpath.php) - 但是你不能只是循環'$ response-> Result'? – DaveRandom 2012-01-16 18:27:52

+0

它比這更復雜,因爲'$ response-> Result'中還有其他子元素。我已經更新了我的問題。 – element119 2012-01-16 18:30:12

+0

[節點名稱上的XPath通配符]的可能重複(http://stackoverflow.com/questions/4203119/xpath-wildcards-on-node-name) – Wrikken 2012-01-16 18:44:47

回答

2
foreach($response->xpath("/Result/*[substring(name(),string-length(name()) - 5) = 'Answer']") as $answer){ 
    echo $answer; 
} 
+0

似乎沒有爲我工作。上面的代碼有可能是錯誤的嗎? – element119 2012-01-16 18:52:42

+0

它在這裏工作,但如果'Result'不是rootnode,則相應地添加正確的路徑(或者,可以用' - > xpath(「// * [substring ....')來啓動它' – Wrikken 2012-01-16 18:55:21

+0

' /'使它相對於查詢?例如,因爲'Result'不是根節點,所以會執行'$ response-> Result-> xpath(「// * [substring ...)'嗎? – element119 2012-01-16 19:00:29