开发者

php getElementsByTagName with specific attribute

开发者 https://www.devze.com 2023-01-26 02:34 出处:网络
I think this gets the first element called <gallery> $gallery = $objDOM->getElementsByTagName(\'gallery\')->item(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[@n开发者_StackOverflow社区ame="Third"]')->item;

Thanks, Andy


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


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.

0

精彩评论

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