In memory download and extract zip archive

后端 未结 4 1915
失恋的感觉
失恋的感觉 2020-12-18 00:13

I would like to download a zip archive and unzip it in memory using PHP.

This is what I have today (and it\'s just too much file-handling for me :) ):



        
相关标签:
4条回答
  • 2020-12-18 00:57

    If you can use system calls, the simplest way should look like this (bzip2 case). You just use stdout.

    $out=shell_exec('bzip2 -dkc '.$zip);
    
    0 讨论(0)
  • 2020-12-18 01:00

    As easy as:

    $zipFile = "test.zip";
    $fileInsideZip = "somefile.txt";
    $content = file_get_contents("zip://$zipFile#$fileInsideZip");
    
    0 讨论(0)
  • 2020-12-18 01:02

    Warning: This cannot be done in memory — ZipArchive cannot work with "memory mapped files".

    You can obtain the data of a file inside a zip-file into a variable (memory) with file_get_contentsDocs as it supports the zip:// Stream wrapper Docs:

    $zipFile = './data/zip.kmz';     # path of zip-file
    $fileInZip = 'test.txt';         # name the file to obtain
    
    # read the file's data:
    $path = sprintf('zip://%s#%s', $zipFile, $fileInZip);
    $fileData = file_get_contents($path);
    

    You can only access local files with zip:// or via ZipArchive. For that you can first copy the contents to a temporary file and work with it:

    $zip = 'http://www.curriculummagic.com/AdvancedBalloons.kmz';
    $file = 'doc.kml';
    
    $ext = pathinfo($zip, PATHINFO_EXTENSION);
    $temp = tempnam(sys_get_temp_dir(), $ext);
    copy($zip, $temp);
    $data = file_get_contents("zip://$temp#$file");
    unlink($temp);
    
    0 讨论(0)
  • 2020-12-18 01:04

    You can get a stream to a file inside the zip and extract it into a variable:

    $fp = $zip->getStream('test.txt');
    if(!$fp) exit("failed\n");
    
    while (!feof($fp)) {
        $contents .= fread($fp, 1024);
    }
    
    fclose($fp);
    
    0 讨论(0)
提交回复
热议问题