简体   繁体   中英

CSV file not downloading PHP

I am trying to export and download a csv file through php. I have done exactly what was suggested in Export to CSV via PHP

I can see my array dump in the response but the csv file is just not downloading. Please Help.

Here is my code:

function download_send_headers($filename) {
// disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

// force download  
    Header('Content-Description: File Transfer');
    header("Content-Type: application/force-download");
    // header("Content-Type: application/octet-stream");
    // header("Content-Type: application/download");

 // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

function array2csv(array &$array)
{
   //   if (count($array) == 0) {
  //     return null;
   //   }
        ob_start();
        $df = fopen("php://output", 'w');
        fputcsv($df, array_keys(reset($array)));
        foreach ($array as $row) {
           fputcsv($df, $row);
        }
        fclose($df);
        return ob_get_clean();
}

Here is how im using it:

download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($modsucc);
die();

This is javascript function:

function exporttocsv(filter){


      var fd = new FormData();
      fd.append('filter', filter);
      fd.append("form", "export_to_csv");
      $.ajax({
        url: getBaseURL()+'assets/handler/OrderManagementHandler.php',
        type: 'POST',   
        data: fd,
        enctype: 'multipart/form-data',
        processData: false, 
        contentType: false,
      })
      .done(function(res) {

        })
        .fail(function() {

        });
}

Handler:

case 'export_to_csv':

    $controller->exportToCSV($_POST);
    break;

Controller:

public function exportToCSV($data){

    $filter = $data['filter'];

    $mod = new OrderManagementModel();
    $modsucc = $mod->exportToCSV($filter);

    if($modsucc){

       // var_dump(ini_get('output_buffering'));
        //var_dump($modsucc);
        download_send_headers("data_export_" . date("Y-m-d") . ".csv");
        echo array2csv($modsucc);
        die();
    }
}

Your code not work because you use ajax and you cant download files with ajax itself, simple way is this:

...
if($modsucc){
    $file = /* directory */"data_export_" . date("Y-m-d") . ".csv";

    $df = fopen(file, 'w');
    fputcsv($df, array_keys(reset($array)));
    foreach ($array as $row) {
        fputcsv($df, $row);
    }
    fclose($df);

    echo $file;
}
...

this will save file, and in your ajax done function:

window.open(res);

this will open new window with address to previously saved file or

window.location.href = res;

this will redirect you to address where the file was saved

to force download you could do it like this:

//force-download.php
if(file_exists($_GET['file'])){
    download_send_headers("data_export_" . date("Y-m-d") . ".csv");
    echo file_get_contents($_GET['file']); // warning: unsafe !! session for example will be better
}

this will send headers for force download and read data from disk where data was previosly saved and echo them

and in your ajax done function:

window.open('force-download.php?file=' + res);

or

window.location.href = 'force-download.php?file=' + res;

this use address where force download headers will be sent

Another possibility is, change $_POST to $_GET and instead of using ajax just redirect to url and it will work with your old code

您的代码可以正常工作,只认为可能是错误的,如果您的服务器未启用输出缓冲并且在调用函数download_send_headers之前输出了某些download_send_headers

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