使用 PHP 创建多个 CSV 文件

Create multiple CSV file with PHP

我正在跟随 this answer 使用 PHP 创建一个 csv 文件。但是我怎样才能创建多个 csv 文件呢?每个人都说那些 csv 文件必须发送到 zip 文件中。但是我不知道怎么办。

我尝试将代码加倍制作2个csv文件,然后在末尾添加this,但下载后zip什么都没有。

首先您需要创建 ZIP 文件夹,创建每个 CSV 并将其保存到临时位置,然后将它们添加到 ZIP,删除临时 CSV 文件,最后下载 ZIP。

因为我不知道你正在使用什么代码,所以这里是一些你应该能够放入你的项目的代码

// 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();