How can error handling be implemented when using xpath() in PHP to avoid issues with extracting specific node values?

When using xpath() in PHP to extract specific node values, it's important to implement error handling to avoid issues such as trying to access a non-existent node or attribute. One way to handle this is by checking if the xpath query returned any results before trying to access the node values.

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

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

// Perform the xpath query
$nodes = $xpath->query('//specific_node');

// Check if any nodes were found
if ($nodes->length > 0) {
    // Access the node values
    foreach ($nodes as $node) {
        $nodeValue = $node->nodeValue;
        // Do something with the node value
    }
} else {
    // Handle the case when no nodes were found
    echo "No specific_node found in the XML.";
}