简体   繁体   中英

PHP Zip Archive is Empty

I need a little help here. I intended to create 2 csv files in PHP and have the browser download them. This will happen when users click a button. However, I discovered that only 1 file download is permitted for each http request. I stumbled upon this stackoverflow post PHP Create Multiple CSV Files in Memory then Compress . The solution creates 3 csv files in-memory and added them into a zip file and download it to the client's browser.

$headers = array('id', 'name', 'age', 'species');
$records = array(
    array('1', 'gise', '4', 'cat'),
    array('2', 'hek2mgl', '36', 'human')
);

// create your zip file
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);

// loop to create 3 csv files
for ($i = 0; $i < 3; $i++) {

    // create a temporary file
    $fd = fopen('php://temp/maxmemory:1048576', 'w');
    if (false === $fd) {
        die('Failed to create temporary file');
    }

    // write the data to csv
    fputcsv($fd, $headers);
    foreach($records as $record) {
        fputcsv($fd, $record);
    }

    // return to the start of the stream
    rewind($fd);

    // add the in-memory file to the archive, giving a name
    $zip->addFromString('file-'.$i.'.csv', stream_get_contents($fd) );
    //close the file
    fclose($fd);
}
// close the archive
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

// remove the zip archive
unlink($zipname);

I tried the solution marked as correct, but it didn't work. A zip file was downloaded, but it is empty.

var_dump($ zip)显示有3个文件。

Any help would be appreciated.

PS : Sorry, bad english, I'm not a native speaker.

Your code is correct. But i also had problems creating the zip-file because of permissions. You need to set right permission of the folder your script is running in and also of the script itself. Assuming you are under linux use chmod recursivly ( -R ):

chmod -R 666 your_folder

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM