fputcsv 后文件为空

File empty after fputcsv

我用 fputcsv 创建了一个文件

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

    // Add the header of the CSV file
    fputcsv($handle, array('Name', 'Surname', 'Age', 'Sex'), ';');
    // Query data from database

    // Add the data queried from database
    foreach ($results as $result) {
        fputcsv(
            $handle, // The file pointer
            array(...), // The fields
            ';' // The delimiter
        );
    }

    file_put_contents('mycsv.csv',fgetcsv($handle), FILE_APPEND);

    fclose($handle);
 ....

我想在 mycsv.csv 上保存输出,但文件为空

php://output 是一个类似于 echoprintstream。这意味着,您正在标准输出中写入(可能是您的控制台或浏览器)。

如果您想将内容写入 csv 文件,请尝试打开此文件或直接使用 PHP 创建它,而不是使用 file_put_contents.

$handle = fopen("mycsv.csv","wb");
fputcsv($handle, array('Name', 'Surname', 'Age', 'Sex'), ';');
//...put your code
rewind($handle);//optional.it will set the file pointer to the begin of the file