What are the best practices for formulating XPath queries in PHP?

When formulating XPath queries in PHP, it is important to follow best practices to ensure efficient and accurate querying of XML documents. To do this, it is recommended to use specific XPath expressions that target the elements or attributes you need, avoid using generic expressions that may return unwanted results, and test your queries thoroughly to ensure they return the desired data.

// Load the XML document
$xml = new DOMDocument();
$xml->load('example.xml');

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

// Define the XPath query
$query = '//book[@category="fiction"]/title';

// Execute the query
$titles = $xpath->query($query);

// Loop through the results
foreach ($titles as $title) {
    echo $title->nodeValue . "\n";
}