How can developers effectively debug issues with DOMXPath queries in PHP?

When debugging issues with DOMXPath queries in PHP, developers can use var_dump() or print_r() to inspect the results of their queries and ensure they are returning the expected data. They can also check for syntax errors in their XPath expressions and make sure they are targeting the correct elements in the DOM. Additionally, developers can use try-catch blocks to handle any exceptions that may be thrown during the query execution.

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);
$query = "//div[@class='example']";

try {
    $result = $xpath->query($query);
    
    if ($result->length > 0) {
        foreach ($result as $node) {
            echo $node->nodeValue . "\n";
        }
    } else {
        echo "No matching elements found.";
    }
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}