2011-11-19 163 views
2

以下功能很好用,但它只能壓縮1個文件夾。我需要壓縮網站根目錄中的幾個特定文件夾,但不是其他所有文件夾。遞歸壓縮多個文件夾

來源:How to [recursively] Zip a directory in PHP?

function Zip($source, $destination) 
{ 
    if (!extension_loaded('zip') || !file_exists($source)) { 
     return false; 
    } 

    $zip = new ZipArchive(); 
    if (!$zip->open($destination, 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)); 
    } 

    return $zip->close(); 

與這家名爲:

Zip('/folder/to/compress/', './compressed.zip'); 

回答

1

如果我理解正確的話,你可以簡單地改變你的代碼,以期望$源是字符串或數組。然後你可以遍歷數組,並添加所有所需的文件夾及其子文件夾

例子:

function Zip($source, $destination) 
{ 
    if (is_string($source)) $source_arr = array($source); // convert it to array 

    if (!extension_loaded('zip')) { 
     return false; 
    } 

    $zip = new ZipArchive(); 
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { 
     return false; 
    } 

    foreach ($source_arr as $source) 
    { 
     if (!file_exists($source)) continue; 
$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)); 
} 

    } 

    return $zip->close(); 

} 

郵編可能是空的所有指定的路徑是無效的,但你可以照顧到這一點。