如何在php中下载创建的CSV文件

时间:2018-03-14 09:44:50

标签: php wordpress

我在php中创建了一个JSON数据,现在需要在点击按钮时下载它。以下是我的代码

function exportPosts($array, $filename, $delimiter){
    header('Content-Type: application/csv');
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    $f = fopen('php://output', 'w');
    // save the column headers
    fputcsv($f, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));
    // Sample data. This can be fetched from mysql too
    $data = array(
        array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
        array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
        array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
        array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
        array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55')
    );

    foreach ($data as $line) {
        fputcsv($f, $line,$delimiter);
    }
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');

    echo readfile($f);
}

函数调用

exportPosts($posts, $filename = "export.csv", $delimiter=",");

以上功能不起作用。请帮我解决这个问题

1 个答案:

答案 0 :(得分:1)

您需要添加Content-Disposition标头。将其添加到header('Content-Type: application/csv');

下方

代码:

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="file.csv"');