0

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

Simon M.
  • 2,244
  • 3
  • 17
  • 34
  • http://stackoverflow.com/questions/8485886/force-file-download-with-php-using-header – Eugen Dec 27 '16 at 12:17
  • http://www.media-division.com/the-right-way-to-handle-file-downloads-in-php/ – Eugen Dec 27 '16 at 12:18
  • Since your CSV generation works but AJAX is getting in the way, it is often recommended around this site to open an iframe or form action with a URL pointing to the PHP script that creates the CSV. The browser itself will then act as you expect and download the file because your headers look correct. http://stackoverflow.com/questions/13039178/download-a-file-built-in-php-output-buffer-from-ajax-call , also http://stackoverflow.com/questions/9353625/php-ajax-force-download – Michael Berkowski Dec 27 '16 at 12:24
  • @Eugen Already tried these header but this didn't worked – Simon M. Dec 27 '16 at 12:25
  • If you pointed your browser directly to the CSV generation URL (without JS/AJAX) right now, I would expect the download to work. Is that correct? – Michael Berkowski Dec 27 '16 at 12:25
  • @MichaelBerkowski I don't have a URL for my CSV file, I don't want to store it somewhere, I just want to build the CSV and then make the browser download it – Simon M. Dec 27 '16 at 13:13

1 Answers1

1

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');
             }
         })
})
Rahul
  • 2,374
  • 2
  • 9
  • 17