In the development process, we often need to perform operations on compressed files, especially when we want to view the file list inside a zip archive. PHP's ZipArchive extension provides a simple tool for handling zip files. This article will explain how to use the ZipArchive class to display the contents of a zip file without extracting it.
The ZipArchive class is a PHP extension used for handling zip files. It supports creating, opening, reading, modifying, and extracting zip files. Below are some common methods:
First, we need to use the open() method of ZipArchive to open a zip file:
<span class="fun">$zip = new ZipArchive();<br>$zip->open('example.zip');</span>
Once the zip file is successfully opened, we can proceed with further operations.
To get the file list from the zip archive, we can use the getNameIndex() method of ZipArchive to loop through the files:
for ($i = 0; $i < $zip->numFiles; $i++) {<br> $filename = $zip->getNameIndex($i);<br> echo $filename . "
";<br>}
This code will print the names of all files in the zip archive.
If you want to retrieve the content of a specific file, you can use the getFromName() method:
<span class="fun">$content = $zip->getFromName('example.txt');<br>echo $content;</span>
This code will output the content of the example.txt file.
Finally, use the close() method to close the zip file:
<span class="fun">$zip->close();</span>
This operation will end the interaction with the zip file.
The following code demonstrates how to display the file list inside the zip archive without extracting the files:
$zip = new ZipArchive();<br>$zip->open('example.zip');<br>for ($i = 0; $i < $zip->numFiles; $i++) {<br> $filename = $zip->getNameIndex($i);<br> echo $filename . "
";<br>}<br>$zip->close();
This code will open a zip file named example.zip and display the list of files inside.
Through this article, you now understand how to use the ZipArchive class in PHP to work with zip files and display their contents without unzipping them. This method is not only simple but also helps developers quickly retrieve basic information from zip archives, enhancing development efficiency.