What are best practices for accessing specific elements within an XML document using XPath in PHP?

When working with XML documents in PHP, XPath can be used to access specific elements within the document. To do this, you need to load the XML document using SimpleXML or DOMDocument, and then use XPath queries to navigate the document and select the desired elements.

// Load the XML document
$xml = new SimpleXMLElement('path/to/xml/file.xml', null, true);

// Use XPath to select specific elements
$elements = $xml->xpath('//element[@attribute="value"]');

// Loop through the selected elements
foreach ($elements as $element) {
    // Do something with the element
    echo $element->nodeValue;
}