简体   繁体   中英

Not able to generate CSV file with php

I want to download csv file using php. Here is what i did

    $filename = $reportof . '.csv';

    header('Content-type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');
    $f = fopen('php://output', 'w');
    $delimiter = ";";

    fputcsv($f, array('ID', 'Name', 'Status', 'Date', 'Rank'));
    foreach ($Reports as $line) {
        fputcsv($f, $line, $delimiter);
    }

Here $Reports contain all data i want on CSV file. I am getting this data in response when i check console->network. But file is not getting downloaded. Can any one suggest me where i went wrong?

Be sure to close the file pointer after you're done writing to it.

$filename = $reportof . '.csv';

header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="' . $filename . '";');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

$f = fopen('php://output', 'w');
ob_clean();

$delimiter = ';';

fputcsv($f, array('ID', 'Name', 'Status', 'Date', 'Rank'));
foreach ($Reports as $line) {
    fputcsv($f, $line, $delimiter);
}

ob_flush();
fclose($f);
die();

Edit:

Added ob_clean() and ob_flush() methods, this is just to make sure any output in you buffer is cleared, this can be skipped if nothing is written prior

Edit 2:

Added some dummy data to test, this works.

header('Content-Description: File Transfer');
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="test.csv";');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

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

$delimiter = ';';

$rs = [
    [1, 'some name1', 'open', date('c'), 1],
    [2, 'some name2', 'closed', date('c'), 2],
    [3, 'some name3', 'open', date('c'), 3],
    [4, 'some name4', 'closed', date('c'), 4],
    [5, 'some name5', 'open', date('c'), 5],
];

fputcsv($f, array('ID', 'Name', 'Status', 'Date', 'Rank'));
foreach ($rs as $line) {
    fputcsv($f, $line, $delimiter);
}

fclose($f);
die();

This downloads the csv automatically:

test.csv

Try opening a new browser window with the URL, using window.open . The browser will probably not make the client open the screen through an AJAX request. Another cause could be your browser trying to display the file in a viewer, which it is not able to do so. Try a different browser?

However, this is still guessing, as you see the contents in the network tab of the inspector and not show us how you call the script...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM