PHP for creating a ZIP archive from a list of files
<?php
// Create a new ZIP archive
$zip = new ZipArchive();
// Open the ZIP archive for writing
if ($zip->open('archive.zip', ZipArchive::CREATE) !== TRUE) {
die("Could not open archive");
}
// Add files to the ZIP archive
$files = ['file1.txt', 'file2.txt', 'file3.txt'];
foreach ($files as $file) {
if ($zip->addFile($file)) {
echo "Successfully added $file to archive\n";
} else {
echo "Failed to add $file to archive\n";
}
}
// Close the ZIP archive
$zip->close();
This script demonstrates how to use the ZipArchive class in PHP to create a ZIP archive from a list of files. Here’s a breakdown of how it works:
-
We start by creating a new ZIP archive using the
ZipArchive
class. -
Next, we open the ZIP archive for writing using the
open()
method. This method takes two parameters: the path to the ZIP archive and the mode in which to open it. In our case, we specifyZipArchive::CREATE
to create a new archive. -
Once the ZIP archive is open, we iterate over the list of files that we want to add to the archive. For each file, we use the
addFile()
method to add it to the archive. This method takes two parameters: the path to the file and the name of the file within the archive. -
After adding all the files to the archive, we close the archive using the
close()
method.
This script provides a simple and effective way to create a ZIP archive from a list of files. It can be easily adapted to meet your specific needs. For example, you could add error handling to the script to handle any errors that may occur while adding files to the archive.