views:

333

answers:

1

I have a script that generates a csv file using the following code:

header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="'.date("Ymdhis").'.csv"');
print $content;

The $content variable simply contains lines with fields separated by commas and then finalised with ."\n"; to generate a new line.

When I open the file in csv it looks fine however, when I try to use the file to import into an external program (MYOB) it does not recognise the End Of Line (\n) character and assumes one long line of text.

When I view the contents of the file in notepad, the end of line character (\n) is a small rectangle box which looks like the character code 0x7F.

If I open the file and re-save it in excel, it removes this character and replaces it with a proper end of line character and I can import the file.

What character do I need to be generating in PHP so that notepad recognises it as a valid End Of Line character? (\n) obviously doesn't do the job.

+2  A: 

Use '\r\n'.

The above is the ascii characters for carriage return + line feed.

Historically this relates to the early days of computing on teletypes when the output was printed to paper and returning the carriage of the teletype head to the start of the line was a separate operation to feeding a line through the printer. You could overwrite lines by just doing a carriage return and insert blank lines by just a line feed. Doing both returned the head to the start of the line and fed it a new line to print on.

What precisely was required differed between systems -

  • Line feed only: - most Unix like systems
  • Carriage return plus Line feed: - DEC amd MS-DOS based systems
  • Carriage return only: - Early Apple/Mac OS's

So what you're generating at the moment is a newline on a Unix system only. Wikipedia has quite a good page on this.

There's actually unix command line tools to do the conversion too. The unix2dos and dos2unix commands convert ascii text files back and forward between the unix and dos formats by converting line feed to line feed plus carriage return and vica versa.

Cruachan