php save csv to zip

Solutions on MaxInterview for php save csv to zip by the best coders in the world

showing results for - "php save csv to zip"
Monica
15 Jan 2016
1// Create ZIP file
2$zipname = storage_path() . '/' . 'zipName.zip';
3$zip = new \ZipArchive;
4
5if ($zip->open($zipname, \ZipArchive::CREATE | \ZipArchive::OVERWRITE) != true) {
6  throw new \Exception('Can\'t save zip file');
7}
8
9// Create CSV file
10$columns = ['id', 'uid', 'name', 'dob'];
11$clientCvs = fopen('php://temp/maxmemory:1048576', 'w');
12if (false === $clientCvs) {
13  throw new \Exception('Failed to create temporary file');
14}
15
16fputcsv($clientCvs, $columns);
17fputcsv($clientCvs, [
18  $this->id,
19  $this->uid,
20  $this->name,
21  $this->dob ?? '-',
22]);
23
24// Rewind stream source
25rewind($clientCvs);
26
27// Add to the zip file
28$zip->addFromString('member.csv', stream_get_contents($clientCvs));
29
30// Close temp file
31fclose($clientCvs);
32