1

I have the following code which exports an array result to csv in PHP:

$file = fopen('php://output', 'w');

    $firstLineKeys = false;
    foreach ($result as $line) {
        if (empty($firstLineKeys))
        {
            $firstLineKeys = array_keys($line);
            fputcsv($file, $firstLineKeys);
            $firstLineKeys = array_flip($firstLineKeys);
        }
        fputcsv($file, $line, ',');
    }

    fclose($file);

However, i get the last line of the csv file as "Headers Sent" which makes the file a little ugly at the end.

How can I remove that last line or not show the message "Headers Sent"?

Tashi
  • 477
  • 4
  • 12

1 Answers1

2

Had to add exit(); at the end. This removed the last line that had "Headers Sent" text.

Solution as follows:

$file = fopen('php://output', 'w');

$firstLineKeys = false;
foreach ($result as $line) {
    if (empty($firstLineKeys))
    {
        $firstLineKeys = array_keys($line);
        fputcsv($file, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
    }
    fputcsv($file, $line, ',');
}

fclose($file);
exit();
Tashi
  • 477
  • 4
  • 12