What potential pitfalls should be considered when writing multi-line text to a .csv file?
When writing multi-line text to a .csv file, it is important to consider that some CSV parsers may not handle multi-line fields correctly. To avoid potential issues, one solution is to enclose the multi-line text within double quotes and replace any existing double quotes within the text with two double quotes. This ensures that the text is properly formatted and can be parsed correctly by CSV readers.
// Example of writing multi-line text to a .csv file
$multiLineText = "This is a multi-line text.\nIt spans across multiple lines.";
$multiLineText = str_replace('"', '""', $multiLineText); // Replace double quotes with two double quotes
$multiLineText = '"' . $multiLineText . '"'; // Enclose text within double quotes
$csvData = [
['Column 1', 'Column 2'],
['Value 1', $multiLineText]
];
$fp = fopen('output.csv', 'w');
foreach ($csvData as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);