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


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

For example:


  <li> lorem </li>

  <li> ipsum </li>

  <li> dolor </li>

  <li> sit </li>


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!


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.


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


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;


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

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




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.


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){
echo $i;


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