doushi9780 2013-05-31 12:06
浏览 29

将文件添加到zip [关闭]

The below code creates a zip file in my own PHP directory, but how can I specify the output folder?

Also, when we extract the zip file, it contains the folder structure of files; how can I prevent this?

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

1条回答 默认 最新

  • douzhuan4406 2013-05-31 12:22
    关注
    /* 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;
        }
    }
    

    Sample Usage

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

    good luck

    评论

报告相同问题?

悬赏问题

  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计