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?
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.
Loop over child nodes and count the
<li>elementsUse XPath to query (and count) only child
<li>elementsResources
childNodespropertynodeNamepropertyDOMXPathclasscount()XPath function