1

if let's say I have

$headers = array(
"userid",
"fname",
"lname");

I want them to placed as header row (topmost part of the csv) separated by comma and enclosed each with double quotes.

I already tried

$fp = fopen('data.csv', 'w+'); 
fputcsv($fp,$headers,',','"');
fclose($fp);

they don't get enclosed with double quotes..how to do it?

sasori
  • 5,249
  • 16
  • 86
  • 138
  • possible duplicate of [Forcing fputcsv to Use Enclosure For \*all\* Fields](http://stackoverflow.com/questions/2489553/forcing-fputcsv-to-use-enclosure-for-all-fields) – Alex Shesterov Nov 23 '14 at 10:16
  • the url you pasted did not provide some help at all – sasori Nov 23 '14 at 10:19
  • because it's not possible. Have you tried manually adding the quotes, like so: `array('"userid'" ...)` – casraf Nov 23 '14 at 10:19
  • @ChenAsraf, if I do that, the output will be like e.g """userid""" – sasori Nov 23 '14 at 10:20
  • 1
    Also try to set the $enclosure parameter to an empty string to not include it in the "needs to be enclosed" characters – casraf Nov 23 '14 at 10:21
  • cool, that helped @ChenAsraf can you put your comment on a separate answer so that I can choose it as best answer? thanks – sasori Nov 23 '14 at 10:24

1 Answers1

2

You may try to force it like so:

$headers = array(
    '"userid"',
    '"fname"',
    '"lname"'
);

By wrapping the values in actual quotes, and then just use a blank enclosure string:

$fp = fopen('data.csv', 'w+'); 
fputcsv($fp,$headers,',','');
fclose($fp);

To force it to exclude your quotes in the "needs to be enclosed" characters (PHP checks if the enclosure character is already inside the string, and escapes+encloses if necessary).

However, in new versions of PHP, you will get this error:

fputcsv(): enclosure must be a character

In which case, I would just recommend doing it yourself, like so:

function put_csv_headers($handle, $headers, $separator, $enclosure) {
    // [add some error checks here, of course]
    array_walk($headers, function(&$item, $i, $enc) {
        $item = $enc . $item . $enc; // wrap the header with the enclosure
    }, $enclosure);
    fputs($handle, implode($separator, $headers));
}

And:

$headers = array('userid', 'fname', 'lname');
$fp = fopen('data.csv', 'w+'); 
put_csv_headers($fp, $headers, ',', '"');
fclose($fp);
casraf
  • 21,085
  • 9
  • 56
  • 91