Php 通过通配符查询循环SimpleXML元素
我有一个来自XML的SimpleXML元素,如下所示:Php 通过通配符查询循环SimpleXML元素,php,xml,xpath,simplexml,Php,Xml,Xpath,Simplexml,我有一个来自XML的SimpleXML元素,如下所示: <Result> <BlueAnswer>Blue</BlueAnswer> <RedAnswer>Red</RedAnswer> <YellowAnswer>Yellow</YellowAnswer> <BlueQuestion>What is my favorite color?</BlueQuesti
<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>
这似乎很简单,但我似乎无法理解。感谢您提前提供的帮助。您可能正在寻找的是-但您不能只循环
$response->Result
?它比这更复杂,因为$response->Result
中还有其他子元素。我已经更新了我的问题。的可能副本似乎对我不起作用。上面的代码可能有错误吗?它在这里工作,但是如果Result
不是根节点,则相应地添加正确的路径(或者,也可以用->xpath(“/*[子字符串….
)开始)/
是否将其设置为相对于查询?例如,由于结果
不是根节点,因此将执行$response->Result->xpath(“/*[子字符串…)
工作?是的,/
在xpaths中的意思是“任何地方”*
“任何名称”。但是,这是昂贵的,因此如果您可以将其定义为/rootnode/second\u node/etc/Result/*
,则更可取。
foreach($response->xpath("/Result/*[substring(name(),string-length(name()) - 5) = 'Answer']") as $answer){
echo $answer;
}
foreach($response->xpath("/Result/*[substring(name(),string-length(name()) - 5) = 'Answer']") as $answer){
echo $answer;
}