What are the best practices for handling namespaces in XML files when using XPath queries in PHP?

When working with XML files that contain namespaces, it is important to properly handle these namespaces in XPath queries in PHP. One common approach is to register the namespaces with a prefix and use that prefix in your XPath queries. This ensures that the XPath queries can correctly target elements within the specified namespaces.

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

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

// Register the namespaces with prefixes
$xpath->registerNamespace('ns', 'http://www.example.com/namespace');

// Use the prefix in your XPath query to target elements within the namespace
$query = '//ns:element';
$elements = $xpath->query($query);

// Loop through the matched elements
foreach ($elements as $element) {
    // Do something with the element
}