2015-04-01 125 views
0

我有一个具有多个路径的数组,我写了创建.zip文件的代码。如何用动态路径或多个路径压缩文件?

这里是代码:

<?php 

$array = array("name" => "/sites/README.txt", 
    "test" => "/sites/chessboard.jpg" 
); 

foreach($array as $key => $value) 
{ 
    $test = $value ; 

    echo "zip started"; 
    $zip = new ZipArchive(); 

    $ow = 1; 
    $file= "/sites/master.zip"; 
    if($zip->open($file,$ow?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)===TRUE) 
    { 
     echo "zip entered to if class"; 

    // Add the files to the .zip file 
     $zip->addFile($test); 
    // $zip->addFile($value); 
    // Closing the zip file 
     $zip->close();  
    } 
} 

?> 

而且问题是在阵列$value具有多个文件路径。 此代码取最后一个文件路径并创建zip。

我想采取所有路径并创建一个zip文件并将其存储在文件夹中。

回答

1

也许这个帮助。将您的循环放在打开的zip语句中。

$array = array("name" => "/sites/README.txt", 
    "test" => "/sites/chessboard.jpg" 
); 
$file= "/sites/master.zip"; 
$zip = new ZipArchive; 
echo "zip started.\n"; 
if ($zip->open($file, ZipArchive::CREATE) === TRUE) { 
    foreach($array as $path){ 
     $zip->addFile($path, basename($path)); 
     echo "$path was added.\n"; 
    } 
    $zip->close(); 
    echo 'done'; 
} else { 
    echo 'failed'; 
} 
0

此代码工作确保您的文件存在或不存在。 和lo

$array = array("sites/README.txt","sites/chessboard.jpg"); 

$zip = new ZipArchive(); // Load zip library 
$zip_name = time().".zip"; // Zip name 
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE) 
{ 
// Opening zip file to load files 
$error .= "* Sorry ZIP creation failed at this time"; 
} 
foreach($array as $key => $value) 
{ 
    if(file_exists($value)){ 
     $zip->addFile($value); // Adding files into zip 
    }else{echo $value ."&nbsp;&nbsp;file not exist<br/>";} 
} 
$zip->close(); 
if(file_exists($zip_name)) 
{ 
    echo "yes";die; 
// push to download the zip 
header('Content-type: application/zip'); 
header('Content-Disposition: attachment; filename="'.$zip_name.'"'); 
readfile($zip_name); 
// remove zip file is exists in temp path 
unlink($zip_name); 
}else{echo "zip not created";die; }