Monday 8 June 2015

Using fputcsv without enclosure

Hi,

If you want to use the PHP function fputcsv in order to create a CSV file using no character as enclosure, you can write:

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd')
);

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

foreach ($list as $fields) {
    fputcsv($fp, $fields, ';', '');
}

But a warning will appear:

PHP Warning:  fputcsv(): enclosure must be a character

To avoid it, you need to write:

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd')
);

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

foreach ($list as $fields) {
    fputcsv($fp, $fields, ';', chr(0));
}

Best regards,
Iban Cardona.

4 comments:

  1. This is dangerous as you are including the character \0 in the output (occuping 1 byte in most of encodings). It will byte you sooner or later.

    ReplyDelete
  2. Hello Jesús,

    Yes, you are right. It is not the best solution but for a small files could be a good workaround.

    Any better suggestion?

    ReplyDelete
  3. do
    fputcsv($fp, $fields, ';', chr(0));
    instead of
    fputcsv($fp, $fields, ';', '');
    then replace
    chr(0) by ''

    ReplyDelete