0

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' => '[email protected]', 'age' => 43),
            array('name' => 'C', 'mail' => '[email protected]', 'age' => 24),
            array('name' => 'B', 'mail' => '[email protected]', 'age' => 35),
            array('name' => 'G', 'mail' => '[email protected]', 'age' => 22),
            array('name' => 'F', 'mail' => '[email protected]', 'age' => 52),
            array('name' => 'D', 'mail' => '[email protected]', 'age' => 32),
            array('name' => 'E', 'mail' => '[email protected]', 'age' => 34),
            array('name' => 'K', 'mail' => '[email protected]', 'age' => 18),
            array('name' => 'L', 'mail' => '[email protected]', 'age' => 25),
            array('name' => 'H', 'mail' => '[email protected]', 'age' => 28),
            array('name' => 'J', 'mail' => '[email protected]', 'age' => 53),
            array('name' => 'I', 'mail' => '[email protected]', 'age' => 26),
        );
        $this->downloadFile($data);
    }
}

$csvDownload = new CsvDownload();
$csvDownload->execute();
1
  • 1
    Don't echo those values, Commented Oct 23, 2020 at 6:47

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.