Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to read a single file inside a zip archive with PHP
To read a single file inside a zip archive, PHP provides a simple stream wrapper syntax that allows you to access files directly without extracting the entire archive.
Syntax
The basic syntax uses the zip:// stream wrapper −
zip://path/to/archive.zip#filename_inside_zip
Example
Here's how to read a specific file from a zip archive using fopen() −
<?php
$handle = fopen('zip://test.zip#test.txt', 'r');
if ($handle) {
$result = '';
while (!feof($handle)) {
$result .= fread($handle, 8192);
}
fclose($handle);
echo $result;
} else {
echo "Failed to open file";
}
?>
Using file_get_contents()
For simpler cases, you can use file_get_contents() directly −
<?php
$content = file_get_contents('zip://test.zip#test.txt');
if ($content !== false) {
echo $content;
} else {
echo "Failed to read file from zip";
}
?>
Key Points
- The
#symbol separates the zip file path from the internal file path - File paths inside the zip are case-sensitive
- Always check if the file handle or content is valid before processing
- The zip file must exist and be readable by PHP
Conclusion
Reading files from zip archives in PHP is straightforward using the zip:// stream wrapper. Use file_get_contents() for simple cases or fopen() for more control over the reading process.
Advertisements
