【问题标题】:How to exclude file in php generated zip如何在php生成的zip中排除文件
【发布时间】:2012-06-13 23:44:28
【问题描述】:

我需要知道如何从 php 生成的 zip 中排除文件/文件夹。这是我的代码:

public function archiveBackup($name = '', $source = '', $destination = '') {
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }
    $zip = new ZipArchive();
    if (!$zip->open($destination.$name, ZIPARCHIVE::CREATE)) {
        return false;
    }
    $source = str_replace('\\', '/', realpath($source));
    if (is_dir($source) === true) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
        foreach ($files as $file) {
            $file = str_replace('\\', '/', realpath($file));
            if(is_dir($file) === true) {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if(is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }       
        }
    }
    else if (is_file($source) === true) {
        $zip->addFromString(basename($source), file_get_contents($source));
    }
    $zip->close();
    return true;
}

示例:我需要排除文件夹“themes”和“style.css”文件,该怎么做?

【问题讨论】:

    标签: php zip zlib


    【解决方案1】:
        $exclude = array('themes', 'style.css');
    
        foreach ($files as $file) {
          if (!in_array($file, $exclude)) {
            $file = str_replace('\\', '/', realpath($file));
            if(is_dir($file) === true) {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if(is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
          }
        }
    

    【讨论】:

    • 如果它工作正常,我可以接受这个答案,但在我的情况下,当文件夹是子文件夹时,这不起作用...... $file 返回字符串值:“/home/user_name/public_html /folder/translations/bg/fields.php”,如果在数组中输入“bg”,这将不起作用。我用正则表达式做,然后脚本工作:)我不知道排除文件夹中是否没有其他文件这可能会工作:)最好的问候:)
    猜你喜欢
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多