2012-03-03 70 views
2

我正在運行一個腳本,ZIP是一個用戶個人目錄,當請求時。PHP .ZIP對象 - str_replace文件夾路徑?

到該目錄的路徑是:

../temp/useremail/

當ZIP真正下載,這也是如何的文件夾路徑出現在它(這顯然看起來很恐怖)。我希望它只顯示爲:

USEREMAIL/

我試着用str_replace函數,但它是無效的。這裏是我的代碼:

$zip = new ZipArchive(); 


$exists = file_exists('../temp/' . $email . '/theme-' . $email . '.zip'); 
$delete = '../temp/' . $email . '/theme-' . $email . '.zip'; 

if($exists) { 
    unlink($delete); 
} 

if ($zip->open('../temp/' . $email . '/theme-' . $email . '.zip', ZIPARCHIVE::CREATE) !== TRUE) { 
    die("Could not open archive"); 
} 

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../temp/$email/")); 

foreach ($iterator as $key => $value) { 
    $_key = str_replace("../temp/'.$email.'/", "", $key); 
    $zip->addFile(realpath($_key), $_key) or die("ERROR: Could not add file: $key"); 
} 

$zip->close(); 
+0

嘗試'ZipArchive :: renameName' - http://www.php.net/manual/en/ziparchive.renamename.php – scibuff 2012-03-03 12:32:44

+0

快速瀏覽,但它似乎沒有幫助,除非我使用它錯的是。你會如何將其整合到我目前的腳本中? – tctc91 2012-03-03 12:48:09

回答

1

你的方式使用str_replace來做到這一點,但你做了一個簡單的錯誤。 在這一行:

$ zip-> addFile(realpath($ _key),$ _key)或die(「ERROR:Could not add file:$ key」);

要修復它,只需將addFile的第一個參數保存爲編輯的$ key(它是系統中文件的較長路徑/實際位置)和第二個參數(zip存檔中的新路徑)!

$zip = new ZipArchive(); 


$exists = file_exists('../temp/' . $email . '/theme-' . $email . '.zip'); 
$delete = '../temp/' . $email . '/theme-' . $email . '.zip'; 

if($exists) { 
    unlink($delete); 
} 

if ($zip->open('../temp/' . $email . '/theme-' . $email . '.zip', ZIPARCHIVE::CREATE) !== TRUE) { 
    die("Could not open archive"); 
} 

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("../temp/$email/")); 

foreach ($iterator as $key => $value) { 
    $_key = str_replace("../temp/'.$email.'/", "", $key); 
    $zip->addFile(realpath($key), $_key) or die("ERROR: Could not add file: $key"); 
} 

$zip->close(); 

就是這樣!

+0

恐怕似乎沒有任何區別。拉鍊結構完全沒有改變。 – tctc91 2012-03-04 16:36:10