Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

Count all HTML tags in page PHP

I spent time on regex to solve this problem but not have result i try solve this problem using PHP 5.3 Information like - How many times repeats in page and information about all tags in page.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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="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
    [title] => 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...