为什么zip文件夹不是用PHP创建的

为什么zip文件夹不是用PHP创建的,php,Php,我正在尝试将一个现有文件夹制作成zip,并使用php下载它。现有文件夹包含一些文件。这是我的密码 $folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']'; $zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']

我正在尝试将一个现有文件夹制作成zip,并使用php下载它。现有文件夹包含一些文件。这是我的密码

$folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']';
$zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.'].zip';

$zip = new ZipArchive; 

if($zip -> open($zip_name, ZipArchive::CREATE ) === TRUE) { 

    $dir = opendir($folder); 

    while($file = readdir($dir)) { 
        if(is_file($folder.$file)) { 
            $zip -> addFile($folder.$file, $file); 
        } 
    } 
    $zip ->close(); 
} 
但是当我调用API时,没有创建zip文件夹。请通读我的代码并帮我解决它。提前感谢

请尝试下面的代码

$folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']';
$zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.'].zip';

$zip = new ZipArchive; 

$zip->open($zip_name, ZipArchive::CREATE);
foreach (glob($folder) as $file) {
    $zip->addFile($file);
}
$zip->close();

您应该避免在名称中使用特殊字符,如
。有些操作系统不支持它。你有错误吗?查看web服务器错误日志?一个好的答案包括对您所做更改及其原因的正确解释。您还将ZipArchive实例化两次。为什么在尝试添加文件之前删除了检查zip存档是否成功创建的
if
-语句?感谢您的回答,但执行此代码后仍无法创建zip文件。我是否需要在开始时启用或添加任何内容(如requre once)?因为答案已经标记@Magnus的第一个目的是创建zip文件。稍后可以添加验证。我可以知道如何在创建zip文件夹后下载它吗?您只需要在代码之后添加它<代码>标题('Content-Type:application/zip')
标题('Content-disposition:attachment;filename=file.zip')
标题('Content-Length:'。文件大小($zipname))
readfile($zipname)
As file.zip是我们初始化的文件名。您可以动态地创建一个。
    // Get real path for our folder
    $rootPath = realpath('folder-to-zip');

    // Initialize archive object
    $zip = new ZipArchive();
    $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

    // Create recursive directory iterator
    /** @var SplFileInfo[] $files */
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($rootPath),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file)
    {
        // Skip directories (they would be added automatically)
        if (!$file->isDir())
        {
            // Get real and relative path for current file
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($rootPath) + 1);

            // Add current file to archive
            $zip->addFile($filePath, $relativePath);
        }
    }

    // Zip archive will be created only after closing object
    $zip->close();