What are the potential pitfalls of using fputcsv for exporting data in PHP?

One potential pitfall of using fputcsv for exporting data in PHP is that it may not handle special characters properly, leading to corrupted data in the exported file. To solve this issue, you can use the mb_convert_encoding function to convert the data to UTF-8 before writing it to the CSV file.

// Open a file for writing
$fp = fopen('export.csv', 'w');

// Write UTF-8 BOM to ensure proper encoding
fwrite($fp, "\xEF\xBB\xBF");

// Iterate over your data array and write each row to the CSV file
foreach ($data as $row) {
    // Convert data to UTF-8 before writing to file
    fputcsv($fp, array_map('utf8_encode', $row));
}

// Close the file
fclose($fp);