What are best practices for handling CSV data and sending emails in PHP to avoid errors in the email content?

When handling CSV data and sending emails in PHP, it's important to properly sanitize and format the data to avoid errors in the email content. One common issue is when special characters or line breaks in the CSV data are not properly escaped or encoded, leading to formatting issues in the email. To solve this, you can use functions like `fputcsv` to properly format the CSV data and `mb_encode_mimeheader` to encode special characters in the email subject.

// Example code snippet to handle CSV data and send email in PHP

// Read CSV data
$csvData = [
    ['John Doe', 'john@example.com'],
    ['Jane Smith', 'jane@example.com'],
];

// Open a temporary file to write CSV data
$csvFile = fopen('php://temp', 'w');
foreach ($csvData as $row) {
    fputcsv($csvFile, $row);
}
rewind($csvFile);

// Prepare email content
$subject = 'CSV Data Report';
$to = 'recipient@example.com';
$headers = 'From: sender@example.com' . "\r\n";
$body = 'Please find attached the CSV data report.';
$attachment = stream_get_contents($csvFile);

// Encode special characters in the email subject
$subject = mb_encode_mimeheader($subject);

// Send email with CSV data attachment
mail($to, $subject, $body, $headers, $attachment);