What is the purpose of using simplexml_load_file() function in PHP to read an XML file and what are the common pitfalls associated with it?

The purpose of using simplexml_load_file() function in PHP is to read an XML file and create a SimpleXMLElement object that can be easily traversed and manipulated. Common pitfalls associated with this function include not checking if the file exists before loading it, not handling errors properly, and not validating the XML structure.

// Read an XML file using simplexml_load_file() function with error handling
$xmlFile = 'data.xml';

if (file_exists($xmlFile)) {
    $xml = simplexml_load_file($xmlFile);
    
    if ($xml === false) {
        die('Error loading XML file');
    }

    // XML processing logic here
} else {
    die('XML file not found');
}