I am trying to make zip of array of files in the same directory format as it is in my computer the script I've written is working the only issue is that it is overwriting the first element of directory with the second one only the last element in the directory array is going in the zip file I need to add all the files from the directory array provided. Here is my code please tell me what am I doing wrong.
// Get real path for our folder
$rootPaths = array(
'D:\xampp\htdocs\moko\wp-content\plugins\moko\classes',
'D:\xampp\htdocs\moko\wp-content\plugins\moko\templates',
);
$valid_files = array();
if (is_array($rootPaths)) {
foreach ($rootPaths as $new_files) {
if (file_exists($new_files)) {
$valid_files[] = $new_files;
}
}
}
// Initialize archive object
if (count($valid_files)) {
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
foreach ($valid_files as $rootPath) {
$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();
}
This script is only creating zip file with the files and directory structure of following directory.
'D:\xampp\htdocs\moko\wp-content\plugins\moko\templates'