0

I'm following this answer to create a csv file with PHP. But how can I create multiple csv files? Everyone said that those csv files must be sent into zip file. But I don't know how to.

I tried to double the code to make 2 csv files, and then add this at the end, but the zip contains nothing after I downloaded it.

Community
  • 1
  • 1
Marsha
  • 167
  • 3
  • 3
  • 18

1 Answers1

2

Firstly you will need to create the ZIP folder, create and save each CSV to a temporary location, then add them to the ZIP, delete the temporary CSV file, and finally download the ZIP.

As I don't know what code you're working with exactly here is some code that you should be able to put into your project

// create the ZIP file
$zip_name = 'csv.zip';
$zip = new ZipArchive;
$zip->open($zip_name, ZipArchive::CREATE);

$files = array('file_1.csv', 'file_2.csv', 'file_3.csv');
$temp_directory = 'path to directory';

// create each CSV file and add to the ZIP folder
foreach($files as $file) {

  $handle = fopen($temp_directory . $file, 'w');

  $data = array(); // data maybe from MySQL to add to your CSV file

  // add your data to the CSV file
  foreach($data as $d) {
    fputcsv($handle, $d);
  }
  fclose($handle);

  // add this file to the ZIP folder
  $zip->addFile($temp_directory . $file);

  // now delete this CSV file
  if(is_file($temp_directory . $file)) {
    unlink($temp_directory . $file);
  }
}

$zip->close();
James Walker
  • 795
  • 2
  • 6
  • 22