如何使用动态路径或多个路径压缩文件?

时间:2015-04-01 06:18:38

标签: php zip

我有一个包含多个路径的数组,我已经为create .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文件并将其存储在文件夹中。

2 个答案:

答案 0 :(得分: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';
}

答案 1 :(得分: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; }