Search code examples
phpzipgzipzlib

How to read a single file inside a zip archive


I need to read the content of a single file, "test.txt", inside of a zip file. The whole zip file is a very large file (2gb) and contains a lot of files (10,000,000), and as such extracting the whole thing is not a viable solution for me. How can I read a single file?


Solution

  • Try using the zip:// wrapper:

    $handle = fopen('zip://test.zip#test.txt', 'r'); 
    $result = '';
    while (!feof($handle)) {
      $result .= fread($handle, 8192);
    }
    fclose($handle);
    echo $result;
    

    You can use file_get_contents too:

    $result = file_get_contents('zip://test.zip#test.txt');
    echo $result;