【问题标题】:Add files to the zip [closed]将文件添加到 zip [关闭]
【发布时间】:2013-05-27 06:02:12
【问题描述】:

下面的代码在我自己的 PHP 目录中创建了一个 zip 文件,但是如何指定输出文件夹?

另外,当我们提取 zip 文件时,它包含文件的文件夹结构;我怎样才能防止这种情况发生?

$zip=new ZipArchive;
$destination1="C:/testfolder/destination/*.*";
$zip->open('file.zip', ZipArchive::CREATE);
foreach (glob($destination1) as $filename)
{
    $zip->addFile($filename);
    echo 'ok';
}

【问题讨论】:

  • 你的问题是?
  • zip 文件应该存在于新目录中。如何为 zip 文件指定新的输出目录???
  • 我也明白了...如果我提取包含 c 文件夹然后测试文件夹然后目标文件夹然后文件的 zip 文件...我的预期输出是 zipfile 应该只包含文件
  • 您想强制用户在他们的计算机中的给定目录中展开 ZIP 吗? (关于文件夹结构,请阅读ZipArchive::addFile() 的文档)。
  • 在 PHP 中,您想访问 PHPNet 以获取所有 PHP 文档。你有很多使用 ZipArchive 类here 的示例。您想阅读所有用户的评论。 Globaly,我用 cmets 找到了所有答案。

标签: php


【解决方案1】:
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { return false; }
    //vars
    $valid_files = array();
    //if files were passed in...
    if(is_array($files)) {
        //cycle through each file
        foreach($files as $file) {
            //make sure the file exists
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //if we have good files...
    if(count($valid_files)) {
        //create the archive
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {
            $zip->addFile($file,$file);
        }
        //debug
        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

        //close the zip -- done!
        $zip->close();

        //check to make sure the file exists
        return file_exists($destination);
    }
    else
    {
        return false;
    }
}

示例用法

$files_to_zip = array(
    'preload-images/1.jpg',
    'preload-images/2.jpg',
    'preload-images/5.jpg',
    'kwicks/ringo.gif',
    'rod.jpg',
    'reddit.gif'
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');

祝你好运

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多