How can the use of DOMXPath in PHP improve the efficiency and flexibility of parsing XML documents compared to the DOMDocument approach?

Using DOMXPath in PHP can improve the efficiency and flexibility of parsing XML documents compared to the DOMDocument approach by allowing for more specific querying of nodes using XPath expressions. This can make it easier to navigate and extract data from complex XML structures, reducing the amount of code needed to achieve the desired results.

// Create a new DOMDocument object
$doc = new DOMDocument();
$doc->load('example.xml');

// Create a new DOMXPath object
$xpath = new DOMXPath($doc);

// Use XPath to query for specific nodes
$nodes = $xpath->query('//book[@category="fiction"]');

// Loop through the results and output the node values
foreach ($nodes as $node) {
    echo $node->nodeValue . "\n";
}