Counting li items from a html file using php
You're close. I think what you're looking for is the following :
$dom = new \DOMDocument();@$dom->loadHTML($html); // or @$dom->loadHTMLFile($filename); if providing filename rather than actual HTML content$count = $dom->getElementsByTagName('li')->length;echo $count;
Depending on your value of $tmp_file
you would use either loadHTML()
if it contains the actual content, or loadHTMLFile()
if it contains the filename. (Note that these methods should not be called statically.)
The method getElementsByTagName()
returns a DOMNodeList
object with a length
property containing the number of found nodes.
You can try the code here.
This DOM parsing approach is preferable to string or regular expression searches since it is designed to account for the many variable ways that HTML may be acceptably written (ie. inconsistent spacing, attribute order).
You can do a very simple Substring Count
for <li>
(or -li-) on that string and it would return the number of items.See here: function.substr-count
$count = substr_count($html,'<li>'); //where $html holds your piece of HTML.
You were close.
Try this:
$count = $dom->getElementsByTagName("li")->length;
And change this echo count($count);
to echo $count