Are there any specific PHP libraries or tools recommended for generating Excel-compatible CSV files with UTF-8 encoding?
When generating Excel-compatible CSV files with UTF-8 encoding in PHP, it is recommended to use the `fputcsv` function along with setting the appropriate headers to ensure proper encoding. Additionally, the `mb_convert_encoding` function can be used to convert the data to UTF-8 if needed.
<?php
// Data to be exported to CSV
$data = [
['Name', 'Age', 'Country'],
['John Doe', 25, 'USA'],
['Jane Smith', 30, 'Canada'],
];
// Set headers for CSV download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// Open output stream
$output = fopen('php://output', 'w');
// Write data to CSV
foreach ($data as $row) {
fputcsv($output, array_map('mb_convert_encoding', $row, array_fill(0, count($row), 'UTF-8'));
}
// Close output stream
fclose($output);
?>