phpexportexport-to-csvfputcsv

PHP fputcsv adds unwanted values


I want to download a CSV file with fputcsv, so far so good, but it adds extra values to the streamed file (Do., Re., Mi., Fa. in this case).

How can I prevent that from happening?

It feels like I'm missing something obvious here. I'm using plain PHP 7.4 without any framework on a Ubuntu machine.

Any help is greatly appreciated!

class CsvDownload
{
    public function downloadFile($data)
    {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=blizzard.csv');
        $fh1 = @fopen('php://output', 'w');
        $headerDisplayed = false;
        foreach ($data as $row) {
            // Add a header row if it hasn't been added yet
            if (!$headerDisplayed) {
                // Use the keys from $data as the titles
                fputcsv($fh1, array_keys($row));
                $headerDisplayed = true;
            }
            // Put the data into the stream
            fputcsv($fh1, $row, ',');
        }
        // Close the file
        fclose($fh1);
        // Make sure nothing else is sent, our file is done
        exit;
    }

    public function execute()
    {
        //Unwanted
        echo "Do.";
        echo "Re.";
        echo "Mi.";
        echo "Fa.";

        $data = array(
            array('name' => 'A', 'mail' => 'a@gmail.com', 'age' => 43),
            array('name' => 'C', 'mail' => 'c@gmail.com', 'age' => 24),
            array('name' => 'B', 'mail' => 'b@gmail.com', 'age' => 35),
            array('name' => 'G', 'mail' => 'f@gmail.com', 'age' => 22),
            array('name' => 'F', 'mail' => 'd@gmail.com', 'age' => 52),
            array('name' => 'D', 'mail' => 'g@gmail.com', 'age' => 32),
            array('name' => 'E', 'mail' => 'e@gmail.com', 'age' => 34),
            array('name' => 'K', 'mail' => 'j@gmail.com', 'age' => 18),
            array('name' => 'L', 'mail' => 'h@gmail.com', 'age' => 25),
            array('name' => 'H', 'mail' => 'i@gmail.com', 'age' => 28),
            array('name' => 'J', 'mail' => 'j@gmail.com', 'age' => 53),
            array('name' => 'I', 'mail' => 'l@gmail.com', 'age' => 26),
        );
        $this->downloadFile($data);
    }
}

$csvDownload = new CsvDownload();
$csvDownload->execute();

Solution

  • I've found the solution to my problem, before doing anything with fputcsv, clean out the buffer with ob_end_clean().

    This way all the previous echo's won't be added to the file.