monkeyUser monkeyUser - 1 month ago 30
PHP Question

File empty after fputcsv

I created a file with 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);
....


I want to save the output on mycsv.csv but the file is empty

Answer

The php://output is a stream that works like echo or print. It means, you are writing in the standard output (maybe, your console or the browser).

If you want to write your content in a csv file, try to open this file or create it using PHP directly, instead of use the file_put_contents.

$handle = fopen("mycsv.csv","wb");
fputcsv($handle, array('Name', 'Surname', 'Age', 'Sex'), ';');
Comments