安装
PHP 5.2.0 以及更新版本方式:
- Linux 系统:为了使用这些函数,必须在编译 PHP 时用--enable-zip配置选项来提供 zip 支持。
- Windows:Windows 用户需要在 php.ini 里使 php_zip.dll 可用,以便使用这些函数。
If installing this in a Docker image using: "docker-php-ext-install zip" you may get an error such as: "docker-php-ext-install zip returned a non-zero code: 1" or "zip support requires ZLIB" Docker documentation now suggests this as the proper way to install, to ensure the dependant libraries are installed with it: # Install zip RUN apt-get update && \ apt-get install -y \ zlib1g-dev && docker-php-ext-install zip
例子
创建一个 Zip 归档
<?php $zip = new ZipArchive(); $filename = "./test112.zip"; if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) { exit("cannot open \n"); } $zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n"); $zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n"); $zip->addFile($thisdir . "/too.php","/testfromfile.php"); echo "numfiles: " . $zip->numFiles . "\n"; echo "status:" . $zip->status . "\n"; $zip->close(); ?>
<?php $zip = zip_open("/tmp/test2.zip"); if ($zip) { while ($zip_entry = zip_read($zip)) { echo "Name: " . zip_entry_name($zip_entry) . "\n"; echo "Actual Filesize: " . zip_entry_filesize($zip_entry) . "\n"; echo "Compressed Size: " . zip_entry_compressedsize($zip_entry) . "\n"; echo "Compression Method: " . zip_entry_compressionmethod($zip_entry) . "\n"; if (zip_entry_open($zip, $zip_entry, "r")) { echo "File Contents:\n"; $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)); echo "$buf\n"; zip_entry_close($zip_entry); } echo "\n"; } zip_close($zip); } ?>