In what situations would using DOMDocument and XPath in PHP be more advantageous than regular expressions for extracting specific data from HTML?
Using DOMDocument and XPath in PHP is more advantageous than regular expressions for extracting specific data from HTML when dealing with complex HTML structures or when the data you need is nested within various HTML elements. DOMDocument allows you to parse and manipulate HTML documents as a tree structure, making it easier to navigate and extract data using XPath queries. XPath provides a more robust and reliable way to target specific elements or attributes within the HTML document compared to regular expressions, which can be error-prone and difficult to maintain.
$html = '<div class="content">
<h1>Title</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$paragraphs = $xpath->query('//div[@class="content"]/p');
foreach ($paragraphs as $paragraph) {
echo $paragraph->nodeValue . "\n";
}