44

When I use fputcsv to write out a line to an open file handle, PHP will add an enclosing character to any column that it believes needs it, but will leave other columns without the enclosures.

For example, you might end up with a line like this

11,"Bob ",Jenkins,"200 main st. USA ",etc

Short of appending a bogus space to the end of every field, is there any way to force fputcsv to always enclose columns with the enclosure (defaults to a ") character?

Alan Storm
  • 161,083
  • 88
  • 380
  • 577
  • Just curious, as my guess is that you're question was in:re to `Magento/Varien_Io_File::streamWriteCsv()` (which ultimately just uses `fputcsv`), did you ever find a good solution for this? Possibly using `Varien_File_Csv`? – pspahn Nov 18 '14 at 19:34
  • @pspahn Never did, (and this was four+ years ago, but I don't think it was specifically Magento related) – Alan Storm Nov 18 '14 at 20:18
  • 1
    Take a look at this custom fputcsv implementation that should fit your needs: https://stackoverflow.com/a/66682050/592868 – Felix Geenen Mar 17 '21 at 22:19

5 Answers5

32

No, fputcsv() only encloses the field under the following conditions

/* enclose a field that contains a delimiter, an enclosure character, or a newline */
if (FPUTCSV_FLD_CHK(delimiter) ||
  FPUTCSV_FLD_CHK(enclosure) ||
  FPUTCSV_FLD_CHK(escape_char) ||
  FPUTCSV_FLD_CHK('\n') ||
  FPUTCSV_FLD_CHK('\r') ||
  FPUTCSV_FLD_CHK('\t') ||
  FPUTCSV_FLD_CHK(' ')
)

There is no "always enclose" option.

VolkerK
  • 93,904
  • 19
  • 160
  • 225
  • 3
    sad, because fgetcsv fails with Österreich without double quotes! – nalply Sep 09 '10 at 12:33
  • 11
    VolkerK is, of course quite right. fputcsv cannot help you with this problem (I have the same issue). Let me help you get a jump start on the next search you will be doing: [http://stackoverflow.com/questions/3933668/convert-array-into-csv](http://stackoverflow.com/questions/3933668/convert-array-into-csv) – ftrotter Mar 13 '12 at 17:59
  • where did you find this? What is your source? – relipse Jun 01 '20 at 15:12
  • 1
    @relipse It's from the php source code, in [/ext/standard/file.c php_fputcsv](https://github.com/php/php-src/blob/master/ext/standard/file.c#L1873) – CollectiveWin Jun 02 '20 at 09:56
21

Not happy with this solution but it is what I did and worked. The idea is to set an empty char as enclosure character on fputcsv and add some quotes on every element of your array.

function encodeFunc($value) {
    return "\"$value\"";
}

fputcsv($handler, array_map(encodeFunc, $array), ',', chr(0));
David d C e Freitas
  • 7,364
  • 4
  • 55
  • 66
  • 3
    Including chr(0) in the file causes issues in some import scripts if the file is UTF-8 – Tom B May 13 '14 at 12:11
  • the csv contain ^@ if you are using chr(0) – Mike Castro Demaria Feb 26 '15 at 19:04
  • 1
    You can get rid of the nulls (chr(0)) in the resulting file by filtering them after you are done outputing your csv: `file_put_contents($file, str_replace(chr(0), '', file_get_contents($file)));`. Also your `encodeFunc` will need to escape double quotes as well if your values have them. See my revision [here](https://gist.github.com/anonymous/223ea7353626bc6a6a9e#file-csvenclosed-php). Other than that it seems to work, just keep in mind it's a hack. – Mahn Sep 26 '15 at 20:22
20

Building on Martin's answer, if you want to avoid inserting any characters that don't stem from the source array (Chr(127), Chr(0), etc), you can replace the fputcsv() line with the following instead:

fputs($fp, implode(",", array_map("encodeFunc", $row))."\r\n");

Granted, fputs() is slower than fputcsv(), but it's a cleaner output. The complete code is thus:

/***
 * @param $value array
 * @return string array values enclosed in quotes every time.
 */
function encodeFunc($value) {
    ///remove any ESCAPED double quotes within string.
    $value = str_replace('\\"','"',$value);
    //then force escape these same double quotes And Any UNESCAPED Ones.
    $value = str_replace('"','\"',$value);
    //force wrap value in quotes and return
    return '"'.$value.'"';
}

$fp = fopen("filename.csv", 'w');
foreach($table as $row){
    fputs($fp, implode(",", array_map("encodeFunc", $row))."\r\n");
}
fclose($fp);
Community
  • 1
  • 1
dearsina
  • 4,065
  • 2
  • 24
  • 31
  • 1
    I did actually find after posting this answer that with `fputcsv` that the function really is pretty lame and using standard *write-to-file* functions as you've also done sorted my code out and sidestepped all issues with CSV consistency across platforms and programs. – Martin Dec 06 '16 at 12:02
  • 2
    Thank you for the good example. I needed to always enclose all values in quotes. And, I needed to force the line endings to CR+LF instead of just LF. This example solves both problems. – Mike Finch Jul 24 '17 at 20:50
3

After a lot of scrafffing around and some somewhat tedious character checking, I have a version of the above referenced codes by Diego and Mahn that will correctly strip out encasings and replace with double quotes on all fields in fputcsv. and then output the file to the browser to download.

I also had a secondary issue of not being able to be sure that double quotes were always / never escaped.

Specifically for when outputting directly to browser using the php://input stream as referenced by Diego. Chr(127) is a space character so the CSV file has a few more spaces than otherwise but I believe this sidesteps the issue of chr(0) NULL characters in UTF-8.

/***
 * @param $value array
 * @return string array values enclosed in quotes every time.
 */
function encodeFunc($value) {
    ///remove any ESCAPED double quotes within string.
    $value = str_replace('\\"','"',$value);
    //then force escape these same double quotes And Any UNESCAPED Ones.
    $value = str_replace('"','\"',$value);
    //force wrap value in quotes and return
    return '"'.$value.'"';
}


$result = $array_Set_Of_DataBase_Results;
$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export-'.date("d-m-Y").'.csv"');
    foreach($result as $row) {
        fputcsv($fp, array_map("encodeFunc", $row), ',', chr(127));
    }
    unset($result,$row);
    die;
}

I hope this is useful for some one.

Community
  • 1
  • 1
Martin
  • 20,858
  • 7
  • 60
  • 113
0

A "quick and dirty" solution is to add ' ' at the end of all of your fields, if it's acceptable for you:

function addspace($v) {
  return $v.' ';
}
fputcsv($handle, array_map('addspace', $fields));

PS: why it's working? see Volkerk answer ;)