首页 > 解决方案 > PHP数组到CSV输出整个html页面

问题描述

我正在尝试使用以下代码使用 PHP 将数组输出到 CSV。但是,它将整个 HTML 页面输出到 CSV。我该如何编写它,以便它只将数组输出到 CSV 而不是页面的代码?

我认为问题与以下有关:

$f = fopen('php://output', 'w');
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    // open raw memory as file so no temp files needed, you might run out of memory though
    $f = fopen('php://output', 'w');
    // loop over the input array
    foreach ($array as $line) { 
        // generate csv lines from the inner arrays
        fputcsv($f, $line, $delimiter); 
    }
    // reset the file pointer to the start of the file
    fseek($f, 0);
    // tell the browser it's going to be a csv file
    header('Content-Type: application/csv');
    // tell the browser we want to save it instead of displaying it
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    // make php send the generated csv lines to the browser
    fpassthru($f);
}

array_to_csv_download($data_array);

标签: phparrayscsv

解决方案


您在标题之前发送输出。

您可以简化为:

<?php
function array_to_csv_download($array, $filename = "export.csv", $delimiter=";") {
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="'.$filename.'";');
    $f = fopen('php://output', 'w');
    foreach ($array as $line)
        fputcsv($f, $line, $delimiter);
}

确保在这些标头调用之前不输出任何其他内容。


推荐阅读