What are the best practices for handling character encoding in CSV files generated with PHP for compatibility with Excel?

When generating CSV files with PHP for compatibility with Excel, it is important to handle character encoding properly to ensure that special characters are displayed correctly. One common practice is to use UTF-8 encoding for the CSV file to support a wide range of characters. This can be achieved by setting the appropriate headers and encoding the data properly before writing it to the CSV file.

// Set headers for CSV file download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=example.csv');

// Open output stream
$output = fopen('php://output', 'w');

// Write UTF-8 BOM to support Excel
fwrite($output, "\xEF\xBB\xBF");

// Data to be written to CSV
$data = array(
    array('Name', 'Age', 'City'),
    array('John Doe', 30, 'New York'),
    array('Jane Smith', 25, 'Los Angeles'),
);

// Encode and write data to CSV
foreach ($data as $row) {
    fputcsv($output, array_map('utf8_encode', $row));
}

// Close output stream
fclose($output);