Write CSV to File Without Enclosures in PHP

Write CSV To File Without Enclosures In 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");

Avoid default quotes from csv file when using fputcsv

Two double-quotes are used to escape double-quotes, so it looks like your date/time is already quoted. If you just want to get a correctly quoted CSV, you could try removing any existing double-quotes (this might be a bit brute force):

$array = array('testname',045645765789,'"04.07.2012 12:10:52"');
$array = str_replace('"', '', $array);

fputcsv($fp, $array);

// Output: testname,79323055,"04.07.2012 12:10:52"

The fputcsv wants to put something around a string with a space in it, so if you want no quotes at all you'll either need to work around or make your own function to do what you want. There are lots of good solutions under this question (edit: this was a different link). Alternately there are a number of other solutions in the comments of the PHP manual.

Based on the first link, you could do:

$array = array('testname',045645765789,'"04.07.2012 12:10:52"');
$array = str_replace('"', '', $array);

fputs($fp, implode(',', $array)."\n");

// Output: testname,79323055,04.07.2012 12:10:52

Create a CSV File for a user in PHP

Try:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

echo "record1,record2,record3\n";
die;

etc

Edit: Here's a snippet of code I use to optionally encode CSV fields:

function maybeEncodeCSVField($string) {
if(strpos($string, ',') !== false || strpos($string, '"') !== false || strpos($string, "\n") !== false) {
$string = '"' . str_replace('"', '""', $string) . '"';
}
return $string;
}

Forcing fputcsv to Use Enclosure For *all* Fields

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.

Generating Csv with PHP - outputting unnecessary quotation marks

Instead of using fputcsv, try implode.

Ref: https://www.php.net/manual/en/function.implode.php

Update 1: You have to be sure that your value does not contain , (comma)

Update 2: If you are concern with the idea about that quoted text will be problem for your CSV datasheet, than you need to know that CSV is designed to that if there is any space between the value. So you don't have to worry about that. Any CSV parser will understand the quoted values properly.



Related Topics



Leave a reply



Submit