4

I'm beginning work on a project that requires that I take multiple arrays and put them in a csv file. However, although it is generating the file, it is generally completely empty(0 b file size). Occasionally, if I miss something, it will put the error message in the file, or a couple times it puts the array in the file as though I had done print_r($array).

currently, I have this:

    <?php

// output headers
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=file.csv');


$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

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


// output data
foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

The arrays used will eventually be generated, but I'm new to generating files, so I wanted to do this first.

I've also tried multiple variations on this, with the same results. So far, the only thing I can think of is that I'm using XAMPP, and that there is some problem with the fputcsv function therein, but I haven't found anybody else with this problem. Is there an error in my code, or should I be looking for my problem elsewhere?

LucenNox
  • 41
  • 1
  • 3
  • If you set your headers like that at the top, won't it spawn an error? – seanbreeden Feb 07 '12 at 20:37
  • Can we see your exact actual code? Presumably the above isn't what you're running, as the "create a file pointer..." line would be a syntax error. Are you expecting the file to be output to disk, or to the http client? Because you're writing to a file, but setting headers like you're expecting it to be output. Also, note that it's good practice to call fclose() on your file, though you don't actually need it in this case, as your handle will be automatically closed at the end of the script. – Matt Gibson Feb 07 '12 at 20:41
  • @seanbreeden-It so far hasn't made any difference where I put it, for better or for worse. – LucenNox Feb 07 '12 at 20:44

2 Answers2

3

fputcsv is meant for writing CSV data to a file.
If you want to write it to STDOUT (which is where data from echo ends up), you'll either have to read it back off the disk, or instead of writing to "file.csv", write to php://stdout.

Either way, don't forget an fclose() at the end.

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
1

Try the example from manual:

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

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

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

fclose($fp);
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
Eugene Manuilov
  • 4,271
  • 8
  • 32
  • 48