Php fputcsv and spanning fields

I was just about to ask the same questions as the question asked here ... Forcing fputcsv to use Enclosure For * all * Fields

The question was

When I use fputcsv to write a string to an open file descriptor, PHP will add a wrapping character for any column that it considers necessary, but leave the other columns without a case.

For example, you can string like this

11, โ€œBob,โ€ Jenkins, โ€œ200 United States Home,โ€ etc.

With the exception of adding dummy space at the end of each field, is there any way to force fputcsv to always enclose columns with a shell (default to ")?

The answer was:

No, fputcsv () limits only 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 option to always attach.

I need to create a CSV file in which any field will be embedded ... What would be the best solution?

Thanks in advance...

+7
php csv fputcsv
source share
2 answers

Minimize your own function - it's not complicated:

  function dumbcsv($file_handle, $data_array, $enclosure, $field_sep, $record_sep) { dumbescape(false, $enclosure); $data_array=array_map('dumbescape',$data_array); return fputs($file_handle, $enclosure . implode($enclosure . $field_sep . $enclosure, $data_array) . $enclosure . $record_sep); } function dumbescape($in, $enclosure=false) { static $enc; if ($enclosure===false) { return str_replace($enc, '\\' . $enc, $in); } $enc=$enclosure; } 

(the above uses unix-style erasure)

FROM.

+7
source share

Workaround: suppose you have data in a two-dimensional array, you can add a string that will lead to citation, and you are sure that it is not contained in your data ("# @@ #" here), and then delete it

  $fp = fopen($filename, 'w'); foreach ($data as $line => $row) { foreach ($row as $key => $value) { $row[$key] = $value."#@ @#"; } fputcsv($fp, $row); } fclose($fp); $contents = file_get_contents($filename); $contents = str_replace("#@ @#", "", $contents); file_put_contents($filename, $contents); 
+1
source share

All Articles