What are the best practices for using XPath in PHP to navigate and extract data from complex XML structures?

When dealing with complex XML structures in PHP, it is best practice to use XPath to navigate and extract data efficiently. By using XPath expressions, you can specify the exact elements or attributes you want to retrieve from the XML document. This helps in simplifying the code and makes it easier to work with nested or deeply structured XML data.

// Load the XML file
$xml = simplexml_load_file('example.xml');

// Use XPath to navigate and extract data
$nodes = $xml->xpath('//book[@category="fiction"]/title');

// Loop through the extracted nodes
foreach ($nodes as $node) {
    echo $node . "\n";
}