What are the advantages of using DOM and XPath for counting HTML elements in PHP compared to manual methods?

When counting HTML elements in PHP, using DOM and XPath provides a more efficient and reliable way to navigate and manipulate the HTML structure compared to manual methods. DOM allows for easy traversal of the HTML document tree, while XPath provides a powerful querying language to select specific elements based on their attributes or structure. This combination simplifies the process of counting elements and ensures accurate results.

$html = '<div><p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p></div>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$elements = $xpath->query('//p');

$count = $elements->length;

echo "Number of <p> elements: " . $count;