How can PHP be used to encode CSV files in UTF-8 to ensure proper display in Excel?
When working with CSV files in PHP that contain special characters or non-ASCII characters, it is important to encode the file in UTF-8 to ensure proper display in Excel. This can be achieved by setting the appropriate HTTP header for encoding and outputting a UTF-8 BOM (Byte Order Mark) at the beginning of the file.
<?php
header('Content-Encoding: UTF-8');
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="example.csv"');
$output = fopen('php://output', 'w');
fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM
// Write your CSV data here
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
fclose($output);
?>