0

I'm outputting a large csv file through standard output (php://output) by using the built-in fputcsv function, but I get a memory error after writing about 14000 lines.

I called ob_end_clean to not use the output buffer, but it doesn't work. Also, I tried flushing the output buffer after every X lines, but it's the same.

Here's a snippet of my code:

function outputCSV($data) {
    ob_end_clean(); //Delete buffer contents and disable output buffering
    $outstream = fopen("php://output", "w");
    function __outputCSV(&$vals, $key, $filehandler) {
        fputcsv($filehandler, $vals);
    }
    array_walk($data, "__outputCSV", $outstream);
    fclose($outstream);
}
Gonzalo
  • 3,674
  • 2
  • 26
  • 28

1 Answers1

0

You'll probably find that you are in a deeper level of output buffering than you realise.

Meaning that your ob_end_clean() is actually only discarding and ending the current level of buffering.

To debug this you could add to your function:

function outputCSV($data) {
    ob_end_clean(); // Delete topmost buffer
    print_r(ob_list_handlers());  // Dump the remaining output buffer handlers
    exit; // Call exit so we can see what's happenining

    // Rest of your code ...
}

If the print_r returns anything but an empty Array(), then you still have one or more levels of output buffering above this. In this case, call ob_end_clean() once more for every buffer.

If the Array() is indeed empty then there may be a different issue and I'm sorry I couldn't help :)

itsmejodie
  • 4,148
  • 1
  • 18
  • 20