简体   繁体   中英

Can't direct download after creating a CSV file

I've seen a lot of answers of this type of questions but none worked for me. I've a CSV object which has a createCSV function like this :

public function createCSV($url, $delimiter = ","){
    $file = fopen($url, 'w');
    foreach ($this->content as $line) {
        fputcsv($file, $line, $delimiter);
    }
    fclose($file);
}

And I want to download it directly from the browser so here is what I do :

  header('Content-type: text/csv');
  header('Content-Disposition: attachment; filename="'.$filename.'"');
  $csv_file->createCSV('php://output');

This part of code is execute with an AJAX call and even if the header is set to text/csv the download doesn't work but in the response tab I can see the content of my csv. I've tried with different header but none of them worked. How can I do to download the CSV ?

EDIT

The thing is that I don't have a URL for my CSV and I don't want to store the file somewhere, I just want to build the file and download directly with the browser

Try this code:

$('#exportcsv').click(function(){
var self = this;
         $.ajax({
             url : '/exportcsv',
             method : 'get',
             success : function(response)
             {
                 console.log(response);
                 var csvData = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response);
                 $(self).attr({
                     'download': 'publisher.csv',
                     'href': csvData,
                     'target': '_blank'
                 });
                 // window.open(uri, 'test.csv');
             }
         })
})

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