Skip to content

Instantly share code, notes, and snippets.

@alexsegura
Last active December 27, 2015 16:49
Show Gist options
  • Save alexsegura/7357978 to your computer and use it in GitHub Desktop.
Save alexsegura/7357978 to your computer and use it in GitHub Desktop.
Simple function to add an entire folder to a ZipArchive. Uses getSubPathName to avoid recreating whole disk structure. Uses iterators, no recursion.
<?php
function addFolderToZip(\ZipArchive $zip, $dir) {
$iterator = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::SELF_FIRST);
$zip->addEmptyDir(basename($dir));
foreach ($iterator as $item) {
if ($item->isDir()) {
$zip->addEmptyDir(basename($dir) . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
} else {
$zip->addFile($item->getPathname(), basename($dir) . DIRECTORY_SEPARATOR . $iterator->getSubPathName());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment