3

I generate csv files with fputcsv and it works just fine, but when I view the csv file in Notepad (Windows) there is no new lines. All lines are in just 1 line, and where the linebreak is supposed to be, there is a sqaure (corrupted character). Other editors on Mac for example show the lines with breaks correctly.

Is there any way to fix this problem as the CSV needs to be imported, and the importer does not see the linebreaks as well.

rkj
  • 556
  • 5
  • 13

3 Answers3

3

http://bugs.php.net/bug.php?id=46367

This is a known and unfixed bug in PHP.

Until they fix it, try using fwrite($fp, '"'.implode('","', str_replace('"', '""', $data_array)).'"'.PHP_EOL);

reukiodo
  • 740
  • 6
  • 12
2

Try using Notepad++ which handles \n newlines more correctly.

Also, see this response inn fputcsv documentation: http://lv.php.net/manual/en/function.fputcsv.php#90883

naivists
  • 32,681
  • 5
  • 61
  • 85
2

put \r\n to end of each line in your code.

Other Quick Fix: Open your generated file in WordPad, it should show them fine, press Cntr+S and now open in notepad, it should show fine in that too.

Edit:

Based on the comments below, just modify your code as follows:

$orders_newlines = array();

foreach($orders as $value)
{
  $orders_newlines[] = $value . "\r\n";

}

Now use $orders_newlines variable instead of $orders in your loop.

Hope that helps.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
  • Inside a foreach I have this: $fp = fopen('exports/export_'.date('Y-d-m-H-i-s').'.csv', 'a'); fputcsv($fp, $orders,';'); where would you put those \r\n? – rkj Mar 04 '10 at 10:13
  • fputcsv($fp, $orders . "\r\n",';'); – Sarfraz Mar 04 '10 at 10:17
  • Warning: fputcsv() expects parameter 2 to be array, string given in /httpd.www/stuff/export.php .. Have to say that $orders is an array. – rkj Mar 04 '10 at 10:19
  • @rkj: see my updated answer and use `$orders_newlines` variable inside `fputcsv` instead of `$orders` variable. – Sarfraz Mar 04 '10 at 10:27
  • @sarfraz this makes every semicolon-seperation on a new line, but at least I now have linebreaks in Notepad too. I'll try modify this to fit my needs. Thank you :) – rkj Mar 04 '10 at 10:39