【问题标题】:Unable to create flat zip file with PHP's ZipArchive无法使用 PHP 的 ZipArchive 创建平面 zip 文件
【发布时间】:2015-04-14 15:06:25
【问题描述】:

我正在尝试使用包含两个 PDF 文件的 PHP ZipArchive 创建一个具有平面文件夹/文件结构的 zip 文件。所以基本上这两个文件都应该在 zip 文件的根目录中。我使用下面的代码来创建 zipfile。

$zip = new ZipArchive();

$zip_filename = "zipfile.zip";

if ($zip->open($zip_filename, ZipArchive::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
}

$zip->addFile("cover_file.pdf", "cover_file.pdf");
$zip->addFile("inlay_file.pdf", "cover_file.pdf");              
$zip->close();

无论我做什么,文件总是放在一个与 zipfile 同名的文件夹中。

有没有办法将文件保存到 zip 文件的根目录?

提前致谢!

【问题讨论】:

  • 你用的是什么版本的php?

标签: php zip ziparchive document-root


【解决方案1】:

对我来说很好用

索引.php

<?php

$zip = new ZipArchive();

if (!$zip->open('zipfile.zip', ZipArchive::CREATE))
    exit("cannot open <$filename>\n");

$zip->addFromString('test.txt', 'tf is this?');
$zip->close();

启动网络服务器

$ php -S localhost:8000

输出是根目录为 test.txt 的 zipfile.zip。

文件夹结构
|--testProject
|----index.php
|----zipfile.zip
压缩文件.zip
|--zipfile.zip
|----test.txt

带有多个文件的示例

<?php

$zip = new ZipArchive();

if (!$zip->open('zipfile.zip', ZipArchive::CREATE))
    exit("cannot open <$filename>\n");

for ($i=0; $i<7; $i++)
    $zip->addFromString("test$i.txt", 'tf is this?');

$zip->close();

输出

|--zipfile.zip
|----text0.txt
|----text1.txt
|----text2.txt
|----text3.txt
|----text4.txt
|----text5.txt
|----text6.txt

注意:此扩展在 php.ini 中没有定义配置指令

在 PHP 5.5.15 上测试

【讨论】:

  • 如果您将单个文件添加到 zip 文件中,它会起作用。只要您添加超过 1 个,它就会创建与 zip 文件同名的文件夹,
  • 不适合我...我刚刚添加了 6 个文件。
猜你喜欢
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2016-06-14
相关资源
最近更新 更多