Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fputcsv and newline codes

I'm using fputcsv in PHP to output a comma-delimited file of a database query. When opening the file in gedit in Ubuntu, it looks correct - each record has a line break (no visible line break characters, but you can tell each record is separated,and opening it in OpenOffice spreadsheet allows me to view the file correctly.)

However, we're sending these files on to a client on Windows, and on their systems, the file comes in as one big, long line. Opening it in Excel, it doesn't recognize multiple lines at all.

I've read several questions on here that are pretty similar, including this one, which includes a link to the really informative Great Newline Schism explanation.

Unfortunately, we can't just tell our clients to open the files in a "smarter" editor. They need to be able to open them in Excel. Is there any programmatic way to ensure that the correct newline characters are added so the file can be opened in a spreadsheet program on any OS?

I'm already using a custom function to force quotes around all values, since fputcsv is selective about it. I've tried doing something like this:

function my_fputcsv($handle, $fieldsarray, $delimiter = "~", $enclosure ='"'){          $glue = $enclosure . $delimiter . $enclosure;      return fwrite($handle, $enclosure . implode($glue,$fieldsarray) . $enclosure."\r\n");  } 

But when the file is opened in a Windows text editor, it still shows up as a single long line.

like image 500
EmmyS Avatar asked Nov 02 '10 17:11

EmmyS


People also ask

How do I read a csv file in column wise in php?

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this: <? php $handle = @fopen("/tmp/inputfile. txt", "r"); if ($handle) { while (($buffer = fgets($handle)) !==


1 Answers

// Writes an array to an open CSV file with a custom end of line. // // $fp: a seekable file pointer. Most file pointers are seekable,  //   but some are not. example: fopen('php://output', 'w') is not seekable. // $eol: probably one of "\r\n", "\n", or for super old macs: "\r" function fputcsv_eol($fp, $array, $eol) {   fputcsv($fp, $array);   if("\n" != $eol && 0 === fseek($fp, -1, SEEK_CUR)) {     fwrite($fp, $eol);   } } 
like image 178
John Douthat Avatar answered Oct 04 '22 00:10

John Douthat