In what scenarios would it be more beneficial to use XPath over regular expressions for data extraction in PHP?

XPath is more beneficial than regular expressions for data extraction in PHP when dealing with structured data in XML or HTML documents. XPath provides a more robust and reliable way to navigate through the document's elements and extract specific data based on their hierarchical relationships, attributes, or values. Regular expressions, on the other hand, are more suitable for pattern matching in unstructured text data.

// Using XPath for data extraction from an XML document
$xml = '<bookstore><book category="fiction"><title>Harry Potter</title><author>J.K. Rowling</author></book></bookstore>';

$doc = new DOMDocument();
$doc->loadXML($xml);

$xpath = new DOMXpath($doc);
$books = $xpath->query('//book');

foreach ($books as $book) {
    $title = $xpath->query('title', $book)->item(0)->nodeValue;
    $author = $xpath->query('author', $book)->item(0)->nodeValue;
    
    echo "Title: $title, Author: $author\n";
}