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

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

我有一个包含多个路径的数组,并且我已经编写了用于创建 .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 文件并将其存储在文件夹中。

也许这有帮助。将循环放在 open 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';
}

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