What are the best practices for maintaining flexibility in PHP code when dealing with XML files?

When dealing with XML files in PHP, it's important to maintain flexibility in your code to handle various XML structures and changes. One way to achieve this is by using XPath queries to navigate through the XML document dynamically, rather than hardcoding specific paths. This allows your code to adapt to different XML structures without requiring manual adjustments.

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

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

// Use XPath to dynamically retrieve the data
$titles = $xml->xpath($query);

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