Write CSV To File Without Enclosures In PHP

2019-01-17 09:19发布

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

11条回答
倾城 Initia
2楼-- · 2019-01-17 09:57

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");
查看更多
Viruses.
3楼-- · 2019-01-17 09:57
<?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',
);
查看更多
孤傲高冷的网名
4楼-- · 2019-01-17 10:01

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

查看更多
放我归山
5楼-- · 2019-01-17 10:04

chr(0) also worked for me:

 fputcsv($fp, $aLine, $sDelimiter, chr(0));
查看更多
女痞
6楼-- · 2019-01-17 10:06

works with chr() function:

fputcsv($f,$array,',',chr(0));
查看更多
你好瞎i
7楼-- · 2019-01-17 10:08

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

查看更多
登录 后发表回答