通过通配符查询循环遍历SimpleXML元素

时间:2012-01-16 18:19:44

标签: php xml xpath simplexml

我有一个SimpleXML元素,来自XML,如下所示:

<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;
}

这看似简单,但我似乎无法弄明白。感谢您提前提供任何帮助。

1 个答案:

答案 0 :(得分:2)

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