What are the best practices for handling errors and warnings when working with SimpleXML in PHP?

When working with SimpleXML in PHP, it is important to handle errors and warnings properly to ensure smooth execution of your code. One way to do this is by setting error handling to catch and handle any warnings or errors that may occur during XML parsing.

// Set error handling to catch and handle warnings or errors
libxml_use_internal_errors(true);

// Load XML file
$xml = simplexml_load_file('example.xml');

// Check for errors
if ($xml === false) {
    // Get and display any errors
    foreach (libxml_get_errors() as $error) {
        echo $error->message;
    }
}

// Clear any errors
libxml_clear_errors();