I want to add subfolder with file to archive.
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
I can't use it, because I don't need all files of my folder. I have array with some information about files:
$paths = [
[
'name' => 'file',
'ext' => 'txt',
'path' => '/folder/'
],
[
'name' => 'subFolder',
'ext' => 'folder',
'path' => '/folder/'
],
[
'name' => 'fileInSubFolder',
'ext' => 'txt',
'path' => '/folder/subFolder/'
]
];
In cycle I do it:
if( $folder[$i]['ext'] == 'folder' )
$zip->addEmptyDir($fileName);
else
$zip->addFromString( $fileName.$fileExt, file_get_contents($fileFullPath.$fileExt));
If "folder", then I create empty folder in archive, else add file to archive. But if file locate in subfolder so file will add to root of archive. And, how can I add file to new empty subfolder? Or how can I change current directory for add file?
You do not "change directory" with ZipArchive you always pass the absolute file path when adding a file.
Now, I'm not sure why you have a $paths
array but then you loop through $folders
since I cannot see all of your code, but if you were looping through your $paths
array you would want to append the absolute path you have stored to the front of the file name.
$paths = [
[
'name' => 'file',
'ext' => 'txt',
'path' => '/folder/'
],
[
'name' => 'subFolder',
'ext' => 'folder',
'path' => '/folder/'
],
[
'name' => 'fileInSubFolder',
'ext' => 'txt',
'path' => '/folder/subFolder/'
]
];
if( $paths[$i]['ext'] == 'folder' ) {
$zip->addEmptyDir($fileName);
} else {
// This would create "/folder/subFolder/fileInSubFolder.txt"
$fullFileName= $paths[$i]['path'] . $paths[$i]['name'] . "." . $paths[$i]['ext'];
$zip->addFromString( $fullFileName, /* File Data Here */);
}