fputcsv后文件为空

时间:2016-10-31 15:51:28

标签: php csv 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上保存输出,但文件是空的

1 个答案:

答案 0 :(得分:1)

php://outputstream,其作用类似于echoprint。这意味着,您正在编写标准输出(可能是您的控制台或浏览器)。

如果要在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