What are some common pitfalls when combining multiple XPath queries in PHP for HTML parsing?

One common pitfall when combining multiple XPath queries in PHP for HTML parsing is not properly chaining the queries together. To ensure accurate results, each subsequent XPath query should be performed on the result of the previous query. This can be achieved by storing the result of each query in a variable and using that variable as the context node for the next query.

// Load HTML content
$html = file_get_contents('example.html');

// Create a new DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);

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

// Perform the first XPath query
$firstQuery = $xpath->query('//div[@class="first"]');

// Check if the first query returned any results
if ($firstQuery->length > 0) {
    // Perform the second XPath query on the result of the first query
    $secondQuery = $xpath->query('.//span[@class="second"]', $firstQuery->item(0));

    // Loop through the results of the second query
    foreach ($secondQuery as $result) {
        // Output the text content of each matching element
        echo $result->nodeValue . "\n";
    }
}