Answers for "php save csv to zip"

PHP
1

php save csv to zip

// Create ZIP file
$zipname = storage_path() . '/' . 'zipName.zip';
$zip = new \ZipArchive;

if ($zip->open($zipname, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) != true) {
  throw new \Exception('Can\'t save zip file');
}

// Create CSV file
$columns = ['id', 'uid', 'name', 'dob'];
$clientCvs = fopen('php://temp/maxmemory:1048576', 'w');
if (false === $clientCvs) {
  throw new \Exception('Failed to create temporary file');
}

fputcsv($clientCvs, $columns);
fputcsv($clientCvs, [
  $this->id,
  $this->uid,
  $this->name,
  $this->dob ?? '-',
]);

// Rewind stream source
rewind($clientCvs);

// Add to the zip file
$zip->addFromString('member.csv', stream_get_contents($clientCvs));

// Close temp file
fclose($clientCvs);
Posted by: Guest on September-02-2021

Browse Popular Code Answers by Language