What are the best practices for handling XML data in PHP, specifically when using xpath?

When handling XML data in PHP, it is important to use the xpath function to efficiently navigate and extract data from the XML structure. To ensure best practices, it is recommended to properly sanitize input data to prevent XPath injection attacks, handle errors gracefully, and optimize xpath queries for performance.

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

// Use xpath to query the XML data
$nodes = $xml->xpath('//book[author="John Doe"]');

// Loop through the results
foreach ($nodes as $node) {
    echo $node->title . "<br>";
}