What are common pitfalls when using DOMDocument / DOMXPath in PHP?

One common pitfall when using DOMDocument / DOMXPath in PHP is not handling errors properly. It's important to check for errors when loading or querying the DOMDocument to avoid unexpected behavior. To solve this, always use try-catch blocks around your DOMDocument operations and handle any potential exceptions.

try {
    $doc = new DOMDocument();
    $doc->loadHTML($html);

    $xpath = new DOMXPath($doc);
    $nodes = $xpath->query('//div[@class="content"]');

    // Check if query was successful before accessing nodes
    if ($nodes !== false) {
        foreach ($nodes as $node) {
            echo $node->nodeValue;
        }
    } else {
        throw new Exception("XPath query failed");
    }
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}