In what scenarios would using DOM/xPath be a better alternative to preg_match_all() in PHP for extracting specific data from HTML?

When extracting specific data from HTML, using DOM/xPath in PHP is a better alternative to preg_match_all() when dealing with complex HTML structures or when the data you need is nested within various tags. DOM/xPath provides a more reliable and efficient way to navigate through the HTML document and extract the desired data.

$html = file_get_contents('https://example.com');

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

$xpath = new DOMXPath($dom);
$elements = $xpath->query('//div[@class="content"]//h2');

foreach ($elements as $element) {
    echo $element->nodeValue . "<br>";
}