What alternative methods or functions can be used to efficiently count all occurrences of a specific tag in a large XML file in PHP?

When dealing with large XML files in PHP, it is important to efficiently count all occurrences of a specific tag without consuming excessive memory. One way to achieve this is by using the XMLReader class, which allows for sequential reading of XML data without loading the entire file into memory. By iterating through the XML file and counting the occurrences of the desired tag, we can achieve the desired result without memory overhead.

$tagToCount = 'example_tag';
$count = 0;

$reader = new XMLReader();
$reader->open('large_file.xml');

while ($reader->read()) {
    if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == $tagToCount) {
        $count++;
    }
}

$reader->close();

echo "Occurrences of '$tagToCount' tag: $count";