PHP fputcsv 添加不需要的值

PHP fputcsv adds unwanted values

我想用 fputcsv 下载一个 CSV 文件,到目前为止还不错,但它会为流式文件添加额外的值(在本例中为 Do.、Re.、Mi.、Fa.)。

我怎样才能防止这种情况发生?

感觉我在这里遗漏了一些明显的东西。我在 Ubuntu 机器上使用没有任何框架的普通 PHP 7.4。

非常感谢任何帮助!

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();

我找到了问题的解决方案,在使用 fputcsv 进行任何操作之前,请使用 ob_end_clean() 清除缓冲区。

这样所有以前的回显都不会添加到文件中。