How can the context of a selected node be maintained when using XPath in a foreach loop in PHP?

When using XPath in a foreach loop in PHP, the context of a selected node can be maintained by storing the node in a variable before entering the loop. This way, the selected node can be accessed within the loop without losing its context.

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

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

// Select the nodes of interest
$nodes = $xpath->query('//some/xpath/expression');

// Store the selected node in a variable
foreach ($nodes as $node) {
    // Access the selected node within the loop
    $selectedNode = $node;
    
    // Perform actions on the selected node
    // Example: echo the node's value
    echo $selectedNode->nodeValue;
}