How can XPath be utilized to efficiently access and modify specific elements in an XML file using PHP?

To efficiently access and modify specific elements in an XML file using PHP, you can utilize XPath expressions to target the desired elements based on their location or attributes within the XML structure. This allows for precise selection and manipulation of data within the XML document.

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

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

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

// Loop through selected elements and modify them
foreach ($elements as $element) {
    // Modify element content or attributes
    $element->nodeValue = 'new value';
}

// Save the modified XML file
$xml->save('example.xml');
?>