
ZipArchive類是專門用於檔案的壓縮與解壓縮操作的類,透過壓縮檔案可以達到節省磁碟空間的目的,並且壓縮檔案體積更小,以便於網路傳輸。
在ZipArchive類別中我們主要使用以下方法:
1:open(開啟一個壓縮套件檔案)
1 2 | $zip = new \ZipArchive;
$zip ->open('test_new.zip', \ZipArchive::CREATE)
|
登入後複製
參數說明:
第一個參數:要開啟的壓縮包檔案
第二個參數:
ZIPARCHIVE::OVERWRITE
總是建立一個新的文件,如果指定的zip檔案存在,則會覆寫。
ZIPARCHIVE::CREATE
如果指定的zip檔案不存在,則新建一個。
ZIPARCHIVE::EXCL
如果指定的zip檔案存在,則會報錯。
ZIPARCHIVE::CHECKCONS
對指定的zip執行其他一致性測試。
(免費學習影片教學分享:php影片教學)
#2:addFile(將指定檔案加入壓縮包)
1 2 | $zip ->addFile('test.txt');
|
登入後複製
3:addEmptyDir (將指定空目錄加入壓縮包)
1 2 | $zip ->addEmptyDir ('newdir');
|
登入後複製
4:addFromString(將指定內容的檔案加入壓縮包)
1 2 | $zip ->addFromString(' new .txt', '要添加到 new .txt文件中的文本');
|
登入後複製
5:extractTO(將壓縮包解壓縮到指定目錄)
1 | $zip ->extractTo('test');
|
登入後複製
6:getNameIndex(根據索引傳回檔案名稱)
7:getStream(根據壓縮內的檔案名稱,取得該檔案的文字流)
1 | $zip ->getStream('hello.txt');
|
登入後複製
8:renameIndex(根據壓縮檔案內的索引(從0開始)修改壓縮檔案內的檔案名稱)
1 2 | /把压缩文件内第一个文件修改成newname.txt
$zip ->renameIndex(0,'newname.txt');
|
登入後複製
9:renameName(根據壓縮檔案內的檔案名,修改壓縮檔案內的檔案名稱)
1 2 | $zip ->renameName('word.txt','newword.txt');
|
登入後複製
10:deleteIndex (根據壓縮檔案內的索引刪除壓縮檔案內的檔案)
11:deleteName(根據壓縮檔案內的文件名刪除檔案)
1 2 | $zip ->deleteName('word.txt');
|
登入後複製
上面是ZipArchive類別的一些常用方法,以下來介紹一些簡單範例:
一:建立一個壓縮套件
#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | $zip = new \ZipArchive;
if ( $zip ->open('test_new.zip', \ZipArchive::CREATE) === true)
{
$zip ->addFile('test.txt');
$zip ->addFile('test.txt', 'newfile.txt');
$zip ->addFile('test.txt', 'test/newfile.txt');
$zip ->addEmptyDir ('test');
$zip ->addFromString(' new .txt', '要添加到 new .txt文件中的文本');
$zip ->addFromString('test/ new .txt', '要添加到 new .txt文件中的文本');
if ( $handle = opendir('images')){
while (false !== ( $entry = readdir( $handle ))){
if ( $entry != "." && $entry != ".." && ! is_dir ('images/' . $entry )){
$zip ->addFile('images/' . $entry );
}
}
closedir ( $handle );
}
$zip ->close();
}
|
登入後複製
二:取得壓縮包的檔案資訊並解壓縮指定壓縮包
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $zip = new \ZipArchive;
if ( $zip ->open( 'test_new.zip' ) === true) {
var_dump( $zip ->getNameIndex(0));
$zip ->extractTo('test');
$stream = $zip ->getStream( 'test.txt' );
$zip ->close();
$str = stream_get_contents( $stream );
var_dump( $str );
}
|
登入後複製
三:修改壓縮包內指定檔案的檔案名稱及刪除壓縮包內指定檔案
1 2 3 4 5 6 7 8 9 10 11 12 13 | $zip = new \ZipArchive;
if ( $zip ->open('test_new.zip') === true) {
$zip ->renameIndex(0,'newname.txt');
$zip ->renameName(' new .txt','newword.txt');
$zip ->deleteIndex(0);
$zip ->deleteName('test.png');
$zip ->close();
}
|
登入後複製
相關文章教學推薦:php教學
#
以上是php利用ZipArchive類別實現檔案壓縮與解壓縮的詳細內容。更多資訊請關注PHP中文網其他相關文章!