What are common pitfalls when exporting data to a CSV file using PHP?
Common pitfalls when exporting data to a CSV file using PHP include not properly formatting the data, not handling special characters or commas within the data, and not setting the correct headers for the CSV file. To solve these issues, make sure to properly format the data with quotes around each value, use functions like `fputcsv()` to handle special characters, and set the headers to indicate that the response is a CSV file.
// Sample PHP code to export data to a CSV file with proper formatting and headers
// Sample data to export
$data = [
['John Doe', 'john.doe@example.com', 'New York'],
['Jane Smith', 'jane.smith@example.com', 'Los Angeles'],
];
// Set headers for CSV file download
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
// Open output stream
$fp = fopen('php://output', 'w');
// Loop through data and write to CSV file
foreach ($data as $row) {
fputcsv($fp, $row);
}
// Close output stream
fclose($fp);