What security considerations should be taken into account when exporting data to a CSV file in PHP to prevent CSV injection attacks?

CSV injection attacks occur when malicious data is inserted into a CSV file, which can lead to code execution or data manipulation when the file is opened in a spreadsheet program. To prevent this, it's important to sanitize the data being exported to the CSV file by escaping special characters and using proper encoding.

// Sanitize and encode data before exporting to CSV file
$csvData = array(
    array('John Doe', 'john.doe@example.com'),
    array('Jane Smith', 'jane.smith@example.com'),
);

$fp = fopen('data.csv', 'w');

foreach ($csvData as $fields) {
    fputcsv($fp, array_map('htmlspecialchars', $fields));
}

fclose($fp);