Count all HTML tags in page PHP

Your question is unfortunately barely understandable in it’s current form. Please try to update it and be more specific. If you want to count all HTML tags in a page, you can do:

$HTML = <<< HTML
<html>
    <head>
        <title>Some Text</title>
    </head>
    <body>
        <p>Hello World<br/>
            <img src="https://stackoverflow.com/questions/3184284/earth.jpg" alt="picture of earth from space"/>
        <p>
        <p>Counting Elements is easy with DOM</p>
    </body>
</html>
HTML;

Counting all DOMElements with DOM:

$dom = new DOMDocument;
$dom->loadHTML($HTML);
$allElements = $dom->getElementsByTagName('*');
echo $allElements->length;

The above will output 8, because there is eight elements in the DOM. If you also need to know the distribution of elements, you can do

$elementDistribution = array();
foreach($allElements as $element) {
    if(array_key_exists($element->tagName, $elementDistribution)) {
        $elementDistribution[$element->tagName] += 1;
    } else {
        $elementDistribution[$element->tagName] = 1;
    }
}
print_r($elementDistribution);

This would return

Array (
    [html] => 1
    [head] => 1
    Count all HTML tags in page PHP => 1
    [body] => 1
    [p] => 2
    [br] => 1
    [img] => 1
)

Note that getElementsByTagName returns DOMElements only. It does not take into account closing tags, nor does it return other DOMNodes. If you also need to count closing tags and other node types, consider using XMLReader instead.

Leave a Comment