2011-08-31 96 views
1

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

例如,如果我有zip文件:

ZIP 
    |-hello.doc 
    |-images 

,我想添加的文件: “example.jpg”,zip文件应该是:

ZIP 
    |-hello.doc 
    |-images 
     |-example.jpg 

感谢帮助

回答

0

邮编功能:

/* 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

3

使用PHP的ZipArchive类:http://us.php.net/manual/en/function.ziparchive-addfile.php 所以,你会做这样的事情:

<?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(); 

现在你的档案库的图像/ example.jpg

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

我确实相信这应该工作。

+0

我太慢了:( – Blaine

+0

您的解决方案创建一个新文件夹,并在该文件夹将文件夹图像与文件名example.jpg。正确的解决方案是没有斜杠你的路径开始。 – Facedown

相关问题