0

I think this gets the first element called <gallery>

$gallery = $objDOM->getElementsByTagName('gallery')->item(0);

I'm trying to get <gallery name="Third">

I think I need something equivalent to:

$gallery = $objDOM->getElementsByTagName('gallery[@name="Third"]')->item;

Thanks, Andy

2 Answers 2

5

This is only possible with DOMXPath, e.g.

$xp    = new DOMXPath($yourDOMDocument);
$nodes = $xp->query('//gallery[@name="Third"]');

or by iterating over the node list after the call to getElementsByTagName with

foreach ($objDOM->getElementsByTagName('gallery') as $gallery) {
    if($gallery->getAttribute('name') === 'Third') {
         // do something
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Using //gallery is different to getElementsByTagName() called on the Document, because it just matches the "gallery"-Elements on the root level, instead of every "gallery"-Element.
@Sebastian not true. //gallery matches any gallery element anywhere in the document (or below a context node). This is equivalent to using getElementsByTagName()
1

As the name suggests getElementsByTagName() only accepts tag names. Try XPath instead

$xpath = new DOMXPath ($objDOM);
$nodeList = $xpath->query('gallery[@name="Third"]');
$gallery = $nodeList->item(0);

Dont tested it, so there may be errors, typos or something.

1 Comment

Of course, don't know why I didn't do it like that in the first place! Cheers.

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.