How can one efficiently navigate through nested elements using DOMXPath in PHP?

When navigating through nested elements using DOMXPath in PHP, it's important to use the correct XPath expressions to target specific elements within the DOM structure. One efficient way to do this is by chaining XPath queries to drill down into the nested elements step by step. By using the `query()` method of DOMXPath with appropriate XPath expressions, you can efficiently navigate through nested elements and retrieve the desired data.

// Load the HTML content into a DOMDocument
$html = '<div><p><span>Hello World!</span></p></div>';
$dom = new DOMDocument();
$dom->loadHTML($html);

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

// Navigate through nested elements using XPath expressions
$elements = $xpath->query('//div/p/span');

// Loop through the matched elements and output their content
foreach ($elements as $element) {
    echo $element->nodeValue; // Output: Hello World!
}