What role does character encoding play in ensuring successful CSV exports from MySQL to Excel using PHP?

Character encoding is crucial in ensuring successful CSV exports from MySQL to Excel using PHP because Excel may not display special characters correctly if the encoding is not set properly. To solve this issue, you can specify the character encoding in the PHP script before exporting the data to CSV.

// Set character encoding to UTF-8
header('Content-Type: text/csv; charset=utf-8');

// Output CSV file
$output = fopen('php://output', 'w');

// Add BOM to fix Excel encoding issue
fwrite($output, "\xEF\xBB\xBF");

// Your MySQL query to fetch data
$query = "SELECT * FROM your_table";
$result = mysqli_query($conn, $query);

// Write data to CSV file
while ($row = mysqli_fetch_assoc($result)) {
    fputcsv($output, $row);
}

// Close the output file
fclose($output);