Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing fputcsv to Use Enclosure For *all* Fields

Tags:

php

csv

fputcsv

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?

like image 840
Alan Storm Avatar asked Mar 22 '10 01:03

Alan Storm


People also ask

What is fputcsv function in PHP?

The fputcsv() function in PHP is an inbuilt function which is used to format a line as CSV(comma separated values) file and writes it to an open file.

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)) !==

How to write into csv file in PHP?

To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file.

How do I add a new row to an existing CSV file in PHP?

Append a new row to the existing CSV file using writerOpen your existing CSV file in append mode Create a file object for this file. Pass this file object to csv.


1 Answers

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.

like image 51
VolkerK Avatar answered Oct 01 '22 14:10

VolkerK