Home » Php » html – PHP – count li elements inside ul

html – PHP – count li elements inside ul

Posted by: admin July 12, 2020 Leave a comment

Questions:

i’m searching for a way to count dynamic li elements inside an ul in php (not js).

For example:

<ul>

  <li> lorem </li>

  <li> ipsum </li>

  <li> dolor </li>

  <li> sit </li>

</ul>

would return me the number 4.
(am i too stupid to use proper code here?)

Is there some way to accomplish that in php?

Thanks in advance!

EDIT:

The markup is generated by a cms system, the count should be placed before the list, inside the template file.

How to&Answers:

You can do a very simple Substring Count for <li> (or -li-) on that string and it would return the number of items.


Edit:

$count = substr_count($html,'<li>'); //where $html holds your piece of HTML.

Answer:

Assuming this HTML is not output by you (otherwise it should be trivial to count the number of elements), you could use PHP’s DOMDocument.

$dom = new DOMDocument;

$dom->loadHTML($str);

foreach($dom->getElementsByTagName('ul') as $ul) {

   $count = $ul->getElementsByTagName('li')->length;

   var_dump($count);

}

CodePad.

This code will count the number of li elements in each ul element. If you don’t care about individual ul elements, just use $dom->getElementsByTagName('li')->length.

Answer:

Your answer lies with DOMDocument.

For example:

$dom = new DOMDocument();
$dom -> loadHTML("<ul><li></li><li></li></ul>");
$li = $dom->getElementsByTagName("li");
foreach ($li as $li_c){
$i++;
}
echo $i;

Answer:

Use PHP’s DOM library, or look up Simple DOM Parser. It contain searches for HTML