如何压缩具有动态路径或多个路径的文件


How to zip a files with dynamic paths or multiple paths?

我有一个具有多个路径的数组,并且我已经为create.zip File编写了代码。

这是代码:

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

而问题是在具有多个文件路径的阵列CCD_ 1中。此代码采用最后一个文件路径并创建zip。

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

也许这会有所帮助。将你的循环放在openzip语句中。

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

此代码正在工作,请确保您的文件是否存在。和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; }