How can the fputcsv() function in PHP be optimized to prevent formatting issues in Excel?

When using the fputcsv() function in PHP to generate CSV files for Excel, it's important to set the correct delimiter and enclosure parameters to prevent formatting issues. By default, Excel expects CSV files to use commas as delimiters and double quotes as enclosures. Setting these parameters correctly in the fputcsv() function will ensure that Excel can properly read and display the data.

$delimiter = ',';
$enclosure = '"';
$handle = fopen('output.csv', 'w');

$data = array(
    array('John Doe', 'john.doe@example.com', '555-1234'),
    array('Jane Smith', 'jane.smith@example.com', '555-5678')
);

foreach ($data as $row) {
    fputcsv($handle, $row, $delimiter, $enclosure);
}

fclose($handle);