What best practices should be followed when appending data from one CSV file to another in PHP, considering differences in data structure?

When appending data from one CSV file to another in PHP, it is important to handle differences in data structure by ensuring that the columns match between the two files. One approach is to read the data from both files, compare the headers, and then append the rows accordingly. Additionally, it is advisable to handle any potential errors or mismatches in the data to prevent issues during the appending process.

$file1 = 'file1.csv';
$file2 = 'file2.csv';

$data1 = array_map('str_getcsv', file($file1));
$data2 = array_map('str_getcsv', file($file2));

$headers1 = array_shift($data1);
$headers2 = array_shift($data2);

if ($headers1 === $headers2) {
    $combinedData = array_merge($data1, $data2);
    
    $outputFile = 'combined.csv';
    $file = fopen($outputFile, 'w');
    
    fputcsv($file, $headers1);
    
    foreach ($combinedData as $row) {
        fputcsv($file, $row);
    }
    
    fclose($file);
} else {
    echo 'Error: Headers do not match between the two files.';
}