I have a textarea submitting to my database on a website that is properly working. But when I generate a CSV (via PHP) from my database, all line breaks will mess up with the resulting CSV. Any CSV reader will interpret the line break from the input into a new line.
I have tried the following approaches:
Encapsulating the fields in quotation marks.
This:
$field = str_replace(array('\n', '\r', '\r\n', '\n\r'), ',', $original_field);
Also this:
$field = strip_tags(nl2br($original_field));
Combining all approaches above.
Anyhow, the ending result will still be a messed up CSV that will break on any line break inputted by user. I have managed to block new line breaks from the text area, but there's a lot of legacy submissions that need me to fix this on the CSV side as well.
Why is it not working? How can I fix this issue?
Press and hold the Alt key and then enter “010” from your keyboard's 10-keypad part.
Place the cursor in the 'Find what' field and use the keyboard shortcut – Control + J (hold the Control key and press the J key). You may not see anything, but this puts the line break character in the 'Find what' field. In the replace field, enter a comma followed by a space character (, ) Click on Replace All.
By default, when you export to CSV files, fields that have multiple lines of text, such as description fields, will be collapsed to a single line of text. This is because such line breaks may cause problems when you import into another application, such as Excel.
In CSV linebreaks are used to separate individual rows, so a linebreak inside a cell may cause problems.
Before accepted answer (of user user1517891
) is not correct, it will replace in string twice, when there is \r\n
... It will replace it as two commas ,
. First it will replace \r
=> ,
, then \n
=> ,
.
You need to use it in different order, as:
$field = str_replace(array("\r\n", "\n\r", "\n", "\r"), ',', $original_field);
I'd suggest using preg_replace()
for this rather than str_replace()
. The reason is that there may be multiple newlines and combinations of \r
and \n
, and I would expect that you'd want to replace them all with just a single comma.
I'd also suggest using trim()
to remove trailing blank lines.
$field = preg_replace('/[\n\r]+/', ',', trim($original_field));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With