What are some best practices to consider when working with DOM manipulation in PHP to avoid unexpected results or errors?

When working with DOM manipulation in PHP, it is important to properly handle errors and unexpected results to ensure the desired outcome. One best practice is to always check if the DOM element exists before attempting to manipulate it to avoid errors.

// Check if the DOM element exists before manipulating it
$dom = new DOMDocument();
$dom->loadHTML($html);

$element = $dom->getElementById('myElement');
if ($element) {
    // Manipulate the element here
    $element->setAttribute('class', 'new-class');
} else {
    // Handle the case when the element does not exist
    echo 'Element not found';
}