What are the advantages of using DOMDocument over preg_match for extracting data from HTML in PHP?

When extracting data from HTML in PHP, using DOMDocument is preferred over preg_match because DOMDocument provides a more reliable and structured way to parse HTML content. DOMDocument allows for easy navigation through the HTML document tree, making it simpler to target specific elements and extract desired data accurately. Additionally, DOMDocument handles malformed HTML more gracefully compared to regular expressions with preg_match.

// Create a new DOMDocument object
$doc = new DOMDocument();

// Load the HTML content from a file or string
$doc->loadHTML($html_content);

// Use DOMXPath to query specific elements
$xpath = new DOMXPath($doc);
$elements = $xpath->query('//div[@class="example"]');

// Loop through the matched elements and extract data
foreach ($elements as $element) {
    echo $element->nodeValue;
}