2015-04-01 124 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; }