1

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

2
  • why did you change from DOM in your last question to SimpleXml now? Commented Nov 19, 2010 at 13:10
  • I was using DOM for adding and deleting nodes because I'd read that it was much easier than with SimpleXML, I am using SimpleXML for displaying and editing the XML. Commented Nov 21, 2010 at 20:15

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

3 Comments

they don't work for me, are you allowed to query for more than one thing in xpath?
@andy see update. "don't work for me" is not a proper error description. please clarify your issues with it.
I'm sorry, I didn't have time to properly check it on Friday. Now I've just had another look and realised I'd changed my XML file and that was why it wasn't working. The xpath stuff was fine all along!! Thanks for your help, Andy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.