How can the output of database content to a .csv file be optimized for compatibility with Excel import and manipulation?

When outputting database content to a .csv file for Excel import, it is important to ensure that the file is formatted correctly to prevent any issues during import and manipulation. To optimize compatibility with Excel, make sure to enclose each field in double quotes, separate fields with commas, and use CRLF (Carriage Return Line Feed) as the line ending.

// Connect to database
$connection = mysqli_connect('localhost', 'username', 'password', 'database');

// Query database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Create and open .csv file
$filename = 'output.csv';
$file = fopen($filename, 'w');

// Output column headers
$headers = ['Column 1', 'Column 2', 'Column 3'];
fputcsv($file, $headers);

// Output database content to .csv file
while ($row = mysqli_fetch_assoc($result)) {
    fputcsv($file, $row);
}

// Close file and database connection
fclose($file);
mysqli_close($connection);