使用PHP将文件添加到zip文件中的文件夹

时间:2011-08-31 00:53:34

标签: php zip

如何使用PHP将文件添加到zip文件中的文件夹?

例如,如果我有zip文件:

myzip.zip
  |-hello.doc

如果我想在“images”文件夹中添加“example.jpg”文件,那么zip文件将是:

myzip.zip
  |-hello.doc
  |-images
    |-example.jpg

我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:4)

使用PHP的ZipArchive类。 Here's the documentation。 所以你会做类似的事情:

<?php

$z = new ZipArchive();
$z->open('/path/to/your/file.zip');
// Notice the second argument which specifies the local path in the archive
$z->addFile('/path/to/example.jpg', 'images/example.jpg');
$z->close();

?>

现在你的档案有“images / example.jpg”。

答案 1 :(得分:0)

Zip功能:

/* 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');

来源:http://davidwalsh.name/create-zip-php

答案 2 :(得分:0)

   if ($zip->open('fileName.zip') === TRUE) {
      $zip->addFile('example.jpg', '/images/example.jpg');
      $zip->close();
      }

我相信这应该有用。