Write CSV To File Without Enclosures In PHP

PhpCsvQuotesQuoting

Php Problem Overview


Is there a native function or solid class/library for writing an array as a line in a CSV file without enclosures? fputcsv will default to " if nothing is passed in for the enclosure param. Google is failing me (returning results for a whole bunch of pages about fputcsv), and PEAR's libraries do more or less the same things as fputcsv.

Something that works exactly like fputcsv, but will allow the fields to remain unquoted.

currently: "field 1","field 2",field3hasNoSpaces

desired: field 1,field 2,field3hasNoSpaces

Php Solutions


Solution 1 - Php

The warnings about foregoing enclosures are valid, but you've said they don't apply to your use-case.

I'm wondering why you can't just use something like this?

<?php
$fields = array(
    "field 1","field 2","field3hasNoSpaces"
);
fputs(STDOUT, implode(',', $fields)."\n");

Solution 2 - Php

works with chr() function:

fputcsv($f,$array,',',chr(0));

Solution 3 - Php

fputcsv($file, $data, ';', chr(127));

Solution 4 - Php

Well car(0) didn't work out as the NULL value will most likely choke most csv parsers.

I ended using fputcsv() to build the initial file, then went through and removed all quotes. Elegant? Maybe not, but it got the job done :).

Solution 5 - Php

Doesn't this work?

fputcsv($fp, split(',', $line),',',' ');

Solution 6 - Php

<?php		
	
$filename = "sample.csv";
$handle = fopen($filename, 'w+');
fputcsv($handle, ['column 1','column 2']);
$data = ['sample','data'];

fputs($handle, implode(',', $data)."\n");

// or

fwrite($handle, implode(',', $data)."\n");

fclose($handle);
$headers = array(
	'Content-Type' => 'text/csv',
);

Solution 7 - Php

I use tricky way to remove double quote, but only in Linux

....
fputcsv($fp, $product_data,"\t");
....
shell_exec('sed -i \'s/"//g\' /path/to/your-file.txt ');

Solution 8 - Php

This is what I use to put standard CSV into an array...

function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
        $resArr = array();
        $n = 0;
        $expEncArr = explode($enclose, $str);
        foreach($expEncArr as $EncItem){
                if($n++%2){
                        array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
                }else{
                        $expDelArr = explode($delim, $EncItem);
                        array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
                        $resArr = array_merge($resArr, $expDelArr);
                }
        }
        return $resArr;
} 

You can then output whatever you want in a foreach loop.

Solution 9 - Php

The downside with a CSV file with no enclosures means an errant comma in user input will munge the row. So you'll need to remove commas before writing a CSV row.

The tricky part with handling CSV is parsing enclosures, which makes the PHP & PEAR CSV functions valuable. Essentially you're looking for a file that is comma-delimited for columns and newline-delimited for rows. Here's a simple starting point:

<?php
$col_separator= ',';
$row_separator= "\n";

$a= array(
 array('my', 'values', 'are', 'awes,breakit,ome'),
 array('these', 'values', 'also', "rock\nAND\nROLL")
);

function encodeRow(array $a) {
 global $col_separator;
 global $row_separator;
 // Can't have the separators in the column data!
 $a2= array();
 foreach ($a as $v) {
  $a2[]= str_replace(array($col_separator, $row_separator), '', $v);
 }
 return implode($col_separator, $a2);
}

$output= array();
foreach ($a as $row) {
 $output[]= encodeRow($row);
}

echo(implode($row_separator, $output));

?>

Solution 10 - Php

Whats wrong with good old fwrite()?

function encloseString($field){
    return ($field) ? '"' . $field . '"' : null;
}

$delimiter = ';';
$data = ["data_field_1", "data_field_2", "data_field_3"];

$fp = fopen("some-file.csv", 'w');

for($i = 0;$i<100000;$i++) {
    fwrite($fp, implode($delimiter, array_map('encloseString', $data) . "\n");
}

fclose($fp);

(Obviously you need to make sure the data in $data is escaped first)

Solution 11 - Php

Chose the solution depends on your application. For some case own code for csv is needed. In case 1 (See result chr0), case 2 (chr127) and case 3 (chr127) the data will be modified(bad thing). Instead use something like this, thanks @oops:

<?php
$fields = array("field 1","field 2","field3hasNoSpaces");
fputs(STDOUT, implode(',', $fields)."\n");
  • case 1. fputcsv($f, $array, $delimiter, car(0)) See result chr0
  • case 2. fputcsv($f, $array, $delimiter, car(127)) chr127
  • case 3. fputcsv($f, $array, $delimiter, ' ') onespace
  • case 4. Own code (s.above inspired by oops or Ansyori or zeros-and-ones ) produces better results.

Solution 12 - Php

chr(0) also worked for me:

 fputcsv($fp, $aLine, $sDelimiter, chr(0));

Solution 13 - Php

Figured it out. By passing in the ascii code for Null to the car() function it seems to work just fine.

fputcsv($f, $array, $delimiter, car(0))

Thanks for the answers everyone!!!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDerek ReynoldsView Question on Stackoverflow
Solution 1 - PhpoopsView Answer on Stackoverflow
Solution 2 - PhpMichal - wereda-netView Answer on Stackoverflow
Solution 3 - PhpRaul DuranView Answer on Stackoverflow
Solution 4 - PhpDerek ReynoldsView Answer on Stackoverflow
Solution 5 - PhpArthur FrankelView Answer on Stackoverflow
Solution 6 - Phpzeros-and-onesView Answer on Stackoverflow
Solution 7 - PhpAnsyoriView Answer on Stackoverflow
Solution 8 - PhpjjclarksonView Answer on Stackoverflow
Solution 9 - PhpleepowersView Answer on Stackoverflow
Solution 10 - PhpMatthew FedakView Answer on Stackoverflow
Solution 11 - PhpJajaView Answer on Stackoverflow
Solution 12 - Phpjb7ANView Answer on Stackoverflow
Solution 13 - PhpDerek ReynoldsView Answer on Stackoverflow