What are some best practices for handling CSV files with PHP, especially when dealing with special characters like commas within the data?

When dealing with CSV files in PHP, especially when handling special characters like commas within the data, it is important to properly escape the data to prevent parsing errors. One common approach is to enclose each field in double quotes and escape any double quotes within the data by doubling them. This ensures that the CSV parser can correctly interpret the data.

// Sample CSV data with special characters
$data = [
    ['Name', 'Email', 'Phone'],
    ['John Doe', 'john.doe@example.com', '123-456-7890'],
    ['Jane, Smith', 'jane.smith@example.com', '456-789-0123'],
];

// Output CSV data with properly escaped special characters
$fp = fopen('output.csv', 'w');
foreach ($data as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);