【问题标题】:PHP Zip Archive is EmptyPHP Zip 存档为空
【发布时间】:2018-04-30 09:00:35
【问题描述】:

我需要一点帮助。 我打算在 PHP 中创建 2 个 csv 文件并让浏览器下载它们。 这将在用户单击按钮时发生。但是,我发现每个 http 请求只允许下载 1 个文件。我偶然发现了这篇 stackoverflow 帖子PHP Create Multiple CSV Files in Memory then Compress。该解决方案在内存中创建 3 个 csv 文件并将它们添加到一个 zip 文件中,然后将其下载到客户端的浏览器中。

$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);

我尝试了标记为正确的解决方案,但没有奏效。 下载了一个 zip 文件,但它是空的。

任何帮助将不胜感激。

PS : 抱歉,英语不好,我不是母语人士。

【问题讨论】:

  • 请提供您的代码的重要/失败部分。
  • 我已经通过添加代码来编辑帖子。很抱歉。

标签: php file csv zip ziparchive


【解决方案1】:

您的代码是正确的。但是由于权限,我在创建 zip 文件时也遇到了问题。您需要设置脚本运行所在文件夹以及脚本本身的正确权限。假设你在 linux 下使用chmod recursivly (-R):

chmod -R 666 your_folder

【讨论】:

  • 没错!!!!!!!!!确实是权限问题。这个问题现在已经解决了。谢谢大佬。
猜你喜欢
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多