Current Location: Home> Latest Articles> How to Search and Extract Files from a ZIP Archive in PHP using ZipArchive

How to Search and Extract Files from a ZIP Archive in PHP using ZipArchive

M66 2025-06-20

How to Search and Extract Files from a ZIP Archive in PHP using ZipArchive

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.

Creating a ZipArchive Object and Opening the ZIP File

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
}

Searching and Extracting a Specific File

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
}

Extracting Multiple Files

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
}

Other Useful Methods

In addition to getFromName and getFromIndex, the ZipArchive class provides other useful methods, such as:

  • count(): Get the number of files in the ZIP archive.
  • getNameIndex(): Get the file name based on the index.

For more information, you can refer to the official PHP documentation.

Closing the ZipArchive Object

After you're done working with the ZIP archive, remember to call the close method to properly close the ZipArchive object:


$zip->close();

Conclusion

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.