Reputation: 2632
To count the number of a specified tag including nested tags, it's simple like this,
<?php
$html = <<<STR
<ul>
<li>item1</li>
<ul>
<li>item2</li>
<li>item3</li>
<li>item4</li>
</ul>
</ul>
STR;
$doc = new DOMDocument;
$doc->loadHTML( $html );
$nodeUl->getElementsByTagName('ul')->item(0);
echo $nodeUl->getElementsByTagName('li')->length;
?>
But if I want to count the li tag in this case only in the first child node, how can it be achieved? I mean in this case it should be only one, not four.
Maybe remove other tags and count it? Or is there a better way of doing it?
Upvotes: 0
Views: 797
Reputation: 51950
The trouble is that getElementsByTagName()
returns all ancestor elements (with the specified tag name), rather than just children.
There are a couple of different approaches that you could take, here are two of them.
<li>
elements$count = 0;
foreach ($nodeUl->childNodes as $child) {
if ($child->nodeName === 'li') {
$count++;
}
}
<li>
elements$xpath = new DOMXPath($doc);
$count = $xpath->evaluate('count(li)', $nodeUl);
childNodes
propertynodeName
propertyDOMXPath
classcount()
XPath functionUpvotes: 1
Reputation: 8818
Try the following:
$doc = new DOMDocument;
$doc->loadHTML($html);
foreach($doc->getElementsByTagName('ul') as $ul) {
$count = $ul->getElementsByTagName('li')->length;
break;
}
Upvotes: 1