我正在開發一個專案,該專案要求我從服務器收集多個檔案,將它們壓縮,然后使用 js-dos 將 zip 安裝為驅動器。
一切都“正確”地作業。在測驗期間,我在 Windows 中手動制作了一個 zip 檔案,代碼運行了。對于最后的測驗,我嘗試掛載 php 生成的 zip,但是在 js-dos 中執行 DIR 時檔案夾結構很奇怪。
我應該有一個包含多個檔案的檔案夾。相反,有幾個相同的檔案夾,里面有一個檔案。
讓我頭疼的是,當我在 winRAR 中打開檔案時它是正確的,但在 js-dos 中它突然不同了。
這是我的代碼,沒什么特別的:
$rootPath = realpath($filefoldername."/");
$zip = new ZipArchive();
$zip->open($filefoldername.'/xp.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$filesZ = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($filesZ as $nameZ => $fileZ)
{
// Skip directories (they would be added automatically)
if (!$fileZ->isDir())
{
// Get real and relative path for current file
$filePath = $fileZ->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();
我猜 windows over 看起來有些東西沒有。用 winRAR 生成的 zip 檔案是可以的,但是這段代碼生成的檔案很奇怪。
我想在 php 中生成 .zip 而不是通過 shell 命令。誰能幫我解決這個問題?
uj5u.com熱心網友回復:
也許js-dos不能自動創建中間目錄,你可以試試下面的代碼將中間目錄添加到zip檔案中。
$rootPath = realpath($filefoldername."/");
$zip = new ZipArchive();
$zip->open($filefoldername.'/xp.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$filesZ = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
// !!!! replace LEAVES_ONLY with SELF_FIRST to include intermediate directories
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($filesZ as $nameZ => $fileZ)
{
// Get real and relative path for current file
$filePath = $fileZ->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) 1);
$relativePath = str_replace('\\', '/', $relativePath);
if ($fileZ->isDir()) {
$zip->addEmptyDir($relativePath);
} else {
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/349369.html
