What are some best practices for accessing nested elements in XML files using PHP's SimpleXML functions?

When working with XML files in PHP using SimpleXML functions, accessing nested elements can sometimes be tricky. To access nested elements, you can use the object-oriented approach by chaining multiple ->children() or ->xpath() calls to navigate through the XML structure. It's important to handle cases where elements may not exist or have different structures in a robust way to avoid errors.

$xml = simplexml_load_file('data.xml');

// Accessing nested elements using object-oriented approach
$nestedElement = $xml->parentElement->childElement->grandchildElement;

// Check if element exists before accessing its value
if ($nestedElement) {
    echo $nestedElement;
} else {
    echo 'Element not found';
}