0

Im using Php (Zend Framework) to download a datagrid as CSV..the csv generation works fine.I just want to know is it possible to download the csv file within a zip file

My current code

public function downloadCsvAction(){
    header("Content-type: application/csv");
        header("Content-Disposition: attachment; filename=answers_csv.csv");
        header("Pragma: no-cache");
        header("Expires: 0");
        echo "stuff1" . ",";
        echo "stuff2".",";
        //----bla bla

   exit;

}

By calling the url controller/downloadCsv im getting a popup to save the csv.I want the csv to be in a zip file

Andy G
  • 19,232
  • 5
  • 47
  • 69
coolguy
  • 7,866
  • 9
  • 45
  • 71

2 Answers2

3

Here is a simple code to zip and output csv as a zip file

//here is your csv file
$csvFile    = "test.csv";

//location for php to create zip file.
$zipPath    = "/tmp/$csvFile.zip";

$zip = new ZipArchive();
if ($zip->open($zipPath,ZipArchive::CREATE)) {
    $zip->addFile($csvFile, $csvFile);
    $zip->close();
    //Make sure the zip file created and output it.
    if(is_file($zipPath)){
        header('Content-type: application/octet-stream; charset=utf-8');
        header('Content-Disposition: attachment; filename="'.$csvFile.'.zip"');
        header('Content-Length: ' . filesize($zipPath));
        readfile($zipPath,false);
    }   
}
Hắc Huyền Minh
  • 1,025
  • 10
  • 13
1

I just want to know is it possible to download the csv file within a zip file

Yes it is possible. Just create a ZIP-file and put the CSV-file in there. Then deliver the ZIP-file.

If you're looking for more technical info, please read into the related Q&A material as the concrete code differs highly on what you need to achieve:

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836
  • a little more info..or link would be perfect :) – coolguy Aug 30 '13 at 10:49
  • @ubercooluk: I suspect the CSV is very large so I assume you want to create the ZIP-file on the fly as well, so please see the edit. – hakre Aug 30 '13 at 10:51
  • Yes the csv is very large(may contains up to 10,000 lines or sometimes 100 lines) ..Thanks for the links ill look into it – coolguy Aug 30 '13 at 10:52
  • is it a good idea to use this way of downloading..for a large file ? – coolguy Aug 30 '13 at 10:53
  • 1
    well, I suppose you want to *stream* it, so anything that works with streaming is a good idea I'd say. You can also temporary create the zipfile on disk and deliver it. However as you only deliver a single file, HTTP compression might be more useful. It depends a bit on what is actually needed and also a bit on the server configuration to really say what a good idea is. – hakre Aug 30 '13 at 10:57