XML 上的 php xpath [英] php xpath on XML
本文介绍了XML 上的 php xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎样才能做到这一点:
How can I achieve this:
<root>
<gallery name="First">
<picture active="1" detail="not shown"/>
<picture active="1" detail="not shown"/>
<picture active="0" detail="not shown"/>
</gallery>
<gallery name="Second">
<picture active="0" detail="not shown"/>
<picture active="1" detail="SHOW THIS ONE"/>
<picture active="1" detail="AND SHOW THIS ONE" />
</gallery>
</root>
我正在尝试:
$myArray = $objXML->xpath('gallery[@name="Second"]/picture[@active=1]');
如何更改它以获得所需的输出?谢谢,安迪
How can I change it to get the desired output? Thanks, Andy
推荐答案
您的 XPath 是错误的.要么使用
Your XPath is wrong. Either use
/root/gallery[@name="Second"]/picture[@active=1]
仅从根节点匹配此节点星座或
to match this node constellation from the root node only or
//gallery[@name="Second"]/picture[@active=1]
匹配文档中任意位置的节点星座(较慢)
to match this node constellation anywhere in the document (slower)
完整的工作示例:
$dom = new DOMDocument;
$dom->load('NewFile.xml'); // containing your XML
$xp = new DOMXPath($dom);
$pictures = $xp->query('/root/gallery[@name="Second"]/picture[@active=1]');
foreach ($pictures as $picture) {
echo $dom->saveXml($picture), PHP_EOL;
}
给予
<picture active="1" detail="SHOW THIS ONE"/>
<picture active="1" detail="AND SHOW THIS ONE"/>
和
$sxe = new SimpleXMLElement('NewFile.xml', NULL, TRUE);
$pictures = $sxe->xpath('/root/gallery[@name="Second"]/picture[@active=1]');
foreach ($pictures as $picture) {
echo $picture['detail'], PHP_EOL;
}
给予
SHOW THIS ONE
AND SHOW THIS ONE
这篇关于XML 上的 php xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文