How can the root folder be excluded from the zip archive when using PHP ZipArchive?

To exclude the root folder from the zip archive when using PHP ZipArchive, you can add the files directly to the archive without including the root folder itself. This can be achieved by iterating over the files within the root folder and adding them individually to the archive.

$zip = new ZipArchive;
$zipFileName = 'archive.zip';
$zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE);

$rootFolder = 'path/to/root/folder';
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootFolder),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach ($files as $file) {
    $localPath = substr($file, strlen($rootFolder) + 1);
    if ($file->isFile()) {
        $zip->addFile($file, $localPath);
    }
}

$zip->close();