【问题标题】:ZipArchive .zip file to show all files in rootZipArchive .zip 文件以显示根目录中的所有文件
【发布时间】:2011-04-15 09:34:27
【问题描述】:

我希望代码将树中的所有文件都制作成根目录中的 .zip 文件

   <?PHP
// create object
$zip = new ZipArchive();

// open archive 
if ($zip->open('my-archive.zip', ZIPARCHIVE::CREATE) !== TRUE) {
    die ("Could not open archive");
}

// list of files to add
// list of files to add
$fileList = array(
    'im/asd.pdf',
    'im/df.pdf',
    'im/d/qoyyum.txt'
);

// add files
foreach ($fileList as $f) {
    $zip->addFile($f) or die ("ERROR: Could not add file: $f");   
}

// close and save archive
$zip->close();
echo "Archive created successfully.";    
?> 

例如文件夹 /im 包含

/im/asd.pdf
/im/df.pdf
/im/d/qoyyum.txt

“my-archive.zip”提取应该如下所示

my-archive/asd.pdf
my-archive/df.pdf
my-archive/qoyyum.txt

我想在提取 zip 时阻止文件夹层次结构。这样每个文件都应该在提取的 zip 文件夹的根目录中

请提出建议

【问题讨论】:

    标签: php compression


    【解决方案1】:

    ZipArchive::addFile() 中有第二个参数称为localname(请参阅here),它允许您在 zip 存档中设置文件的本地名称。使用它来覆盖默认的目录结构。

    foreach ($fileList as $f) {
        $filename_parts = explode('/', $f);  // Split the filename up by the '/' character
        $zip->addFile($f, end($filename_parts)) or die ("ERROR: Could not add file: $f");   
    }
    

    【讨论】:

    • 除了explode和end()之外,还可以使用basename()函数获取文件名
    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 2021-01-06
    • 2018-02-12
    • 2012-06-15
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多