开发者

php xpath on XML

How can I achiev开发者_如何学Pythone 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>

I'm trying:

$myArray = $objXML->xpath('gallery[@name="Second"]/picture[@active=1]');

How can I change it to get the desired output? Thanks, Andy


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)

Full working examples:

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

gives

<picture active="1" detail="SHOW THIS ONE"/>
<picture active="1" detail="AND SHOW THIS ONE"/>

and

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

gives

SHOW THIS ONE 
AND SHOW THIS ONE
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜