Kaushtuv
Kaushtuv

Reputation: 489

Remove line break for csv import

I have a text field in the database with datatype also as text. It holds comments and stuff. Now when I read this and export in a csv if it finds a new line in that comment such as

This is a comment

This is another line

The csv import show "This is another line" in next line and thus mess up my data.

So far I have tried str_replace(), trim(). Still don't seem to do anything. I have looked for similar answers in stackoverflow but couldn't find one that suits my problem

Thanks

Upvotes: 1

Views: 6590

Answers (2)

Graham
Graham

Reputation: 1749

If you convert your newlines to printf-style strings, you can avoid this problem.

<?php

$t='This is a comment

This is another line
';

print str_replace("\n","\\n",$t);

Output:

This is a comment\n\nThis is another line\n

Also look in to htmlspecialchars(). You need to protect other characters that could break your CSV.

Lastly, have a close look at fputcsv() to see if it'll do what you need. Might be better to use builtins than to roll your own.

Upvotes: 0

ckaufman
ckaufman

Reputation: 1497

What are you searching for in the str_replace function? You should be able to search for "\r" and or "\n" the the given string. Examples are documented in the PHP str_replace documentation. Example links below:

http://php.net/manual/en/function.str-replace.php#example-4450

http://www.php.net/manual/en/function.str-replace.php#97374

Upvotes: 3

Related Questions