What best practices should be followed when handling nested XML elements in PHP for CSV conversion?

When handling nested XML elements in PHP for CSV conversion, it is important to properly traverse the XML structure to extract the necessary data. One common approach is to use recursion to handle nested elements and flatten the structure into a format suitable for CSV conversion. Additionally, it is important to handle any special characters or formatting issues that may arise during the conversion process.

function xmlToCsv($xml, $csvFile) {
    $xml = simplexml_load_string($xml);
    
    $csvData = [];
    
    foreach ($xml->children() as $child) {
        $rowData = [];
        parseXml($child, $rowData);
        $csvData[] = $rowData;
    }
    
    $fp = fopen($csvFile, 'w');
    
    foreach ($csvData as $row) {
        fputcsv($fp, $row);
    }
    
    fclose($fp);
}

function parseXml($xml, &$data) {
    foreach ($xml->children() as $child) {
        if ($child->count() > 0) {
            parseXml($child, $data);
        } else {
            $data[] = (string) $child;
        }
    }
}

// Usage example
$xmlData = file_get_contents('data.xml');
xmlToCsv($xmlData, 'output.csv');