ZipArchive is a powerful class in PHP used for creating, reading, and extracting files from ZIP archives. In this article, we'll explain how to use the ZipArchive class to search for and extract files from a ZIP archive, with relevant code examples.
First, we need to create a ZipArchive object and open a ZIP file. Below is the code to open the archive:
$zip = new ZipArchive;
$filename = 'example.zip';
if ($zip->open($filename) === true) {
// The ZIP file was successfully opened
} else {
// Failed to open, handle the error
}
Next, we can use the getFromName method of the ZipArchive class to search for and extract a file from the ZIP archive. This method requires the filename of an existing file in the archive as a parameter and returns the file's content. Below is the code:
$fileContent = $zip->getFromName('example.txt');
if ($fileContent !== false) {
// The file exists in the ZIP archive
// You can further process $fileContent, such as saving it to disk or outputting it to the client
} else {
// The file does not exist in the archive, handle the error
}
If we need to extract multiple files from the ZIP archive, we can use the getFromIndex method. This method requires the index position of an existing file in the archive. The index starts from 0. Here's the code:
$fileContent = $zip->getFromIndex(0);
if ($fileContent !== false) {
// The file exists in the ZIP archive
// You can further process $fileContent, such as saving it to disk or outputting it to the client
} else {
// The file does not exist in the archive, handle the error
}
In addition to getFromName and getFromIndex, the ZipArchive class provides other useful methods, such as:
For more information, you can refer to the official PHP documentation.
After you're done working with the ZIP archive, remember to call the close method to properly close the ZipArchive object:
$zip->close();
In this article, we've demonstrated how to easily search for and extract files from a ZIP archive using PHP's ZipArchive class. Whether extracting a single file or multiple files, ZipArchive offers an efficient way to work with compressed archives. We hope this article helps you in your PHP development projects.