Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to remove linebreaks from a csv file? 2

Status
Not open for further replies.

dcnguyen

Technical User
Mar 22, 2005
54
0
0
US
I converted a database to csv format and found out that some of the textfields have irregular line breaks. For example, the ideal format would be:

"Apple", "10", "There were ten apples in the orchard"


What some of the entries end up being are:

"Apple", "10", "There are ten
apples in the
orchard
"

Is there anyway with php that I can go through to fix these kind of irregular entries? I was hoping doing a fgetcsv would preserve the original columns, but I get a result like:

Array(
[0]=>"Apple"
[1]=>"10"
[2]=>"There are ten
)
Array(
[0]=>apples in the
)
Array(
[0]=>orchard
)
Array(
[0]=>"
)
 
You could try something like:
Code:
$nolinebreaks=str_replace("\n\r"," ",$csvfilecontents);

But it's going to be hard to distinguish the incorrect line breaks from the correct ones.






----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
fgetcsv will work just fine. you just need to give it the right parameters
Code:
$fh = fopen("somefile.txt");

while ( ($row = fgetcsv($fh, 2084, ',', '"') !== false){
  //do stuff
}

remember to convert the line breaks to <br> tags if you want to preserve them within an html block. use nl2br() for this.
 
Right sorry my mistake. [red] \r\n. [/red]

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Thanks all, for the help. I used a combination of the two...using fgetcsv to split the fields properly, then using str_replace to weed out the linebreaks in the affected field. I found that I had to delimit my file differently...that is, I used pipes to delimit, and ^ to set off text blocks...Using quotation marks caused problems since some of the text entries had quotation marks (and MSAcess wasn't escaping them)
 
for compatibility with excel etc you might be better served with cleansing the data (i.e. escaping it). it's a once only process, of course and would not be difficult
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top