Teno
Teno

Reputation: 2632

Count the Number of Specified Tags in the First Child Node in PHP

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

Answers (2)

salathe
salathe

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.

Loop over child nodes and count the <li> elements

$count = 0;
foreach ($nodeUl->childNodes as $child) {
    if ($child->nodeName === 'li') {
        $count++;
    }
}

Use XPath to query (and count) only child <li> elements

$xpath = new DOMXPath($doc);
$count = $xpath->evaluate('count(li)', $nodeUl);

Resources

Upvotes: 1

Conrad Lotz
Conrad Lotz

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

Related Questions