This article mainly introduces php ZipArchive class usage examples, and describes in detail how to operate zip files in the ZipArchive class, for more information about php ZipArchive usage, see the following example. The details are as follows:
Generally, php5.2 supports the ZipArchive class, and php4 can only use the zip function. In fact, before the official implementation of the zip class, Daniel has contributed to the packaging and decompression of the zip file. Now php contains the ZipArchive class, which is preferred. This class can be used to create and decompress zip files and directly read the content in the zip package, which is very convenient. here we mainly summarize the process of reading and decompressing.
Decompress a package to the specified directory:
The code is as follows:
<? Php
$ Zip = new ZipArchive;
If ($ zip-> open('test.zip ') === TRUE ){
$ Zip-> extracelist ('/my/destination/dir /');
$ Zip-> close ();
Echo 'OK ';
} Else {
Echo 'failed ';
}
?>
If you only need to read the content of a file in the package, you need the file name or the index value of the file.
The code is as follows:
<? Php
$ Zip = new ZipArchive;
If ($ zip-> open('test.zip ') === TRUE ){
Echo $ zip-> getFromName ('example. php ');
$ Zip-> close ();
}
?>
If example. php is in a directory, you must add a path to obtain the content.
If you only know the file name, but do not know the specific path of the file, you can search for the index of the specified file name, and then retrieve the content by the index.
The code is as follows:
<? Php
$ Zip = new ZipArchive;
If ($ zip-> open('test.zip ') === TRUE ){
$ Index = $ zip-> locateName ('example. php', ZIPARCHIVE: FL_NOCASE | ZIPARCHIVE: FL_NODIR );
$ Contents = $ zip-> getFromIndex ($ index );
}
?>
The locateName method is used to obtain the index. if a file with the same name exists in multiple paths in the compressed package, it seems that only the first index can be returned. to obtain the index of all files with the same name, you can only use the stupid method, loop search.
The code is as follows:
<? Php
$ Zip = new ZipArchive;
If ($ zip-> open('test.zip ') === TRUE ){
For ($ I = 0; $ I <$ zip-> numFiles; $ I ++)
{
If (substr_count ($ zip-> getNameIndex ($ I), 'example. php')> 0 ){
$ Contents = $ zip-> getFromIndex ($ I );
}
}
}
?>
I hope this article will help you with php programming.