简体   繁体   中英

php xpath on XML

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM