Zi 字媒體
2017-07-25T20:27:27+00:00
Use Zip Archive with PHP
PHP:8.0
在 PHP 中,要實作 Zip 壓縮和解壓縮檔案功能的話,可以透過 PHP ZipArchive 實作。
Basic Usage
基本使用
$zipname = 'test.zip';
$files = ['example.xlsx', 'example.xlsx'];
$zip = new ZipArchive();
// Open Zip file
$res = $zip->open($zipname, ZipArchive::CREATE);
if ($res) {
// Add File
foreach ($files as $file) {
// zip file
$fileName = $file;
$zip->addFile($file, $fileName);
}
// Add Directory
$zip->addEmptyDir('test-dir');
$zip->addFile('example.xlsx', 'test-dir/example.xlsx');
}
// Close file
$zip->close();
On the Fly
有時候在實作下載功能時,不一定要存成檔案,可以以 Streaming 的形式實作。
// Create tmp
$file = tempnam("/tmp", "zip");
$zip = new ZipArchive;
$res = $zip->open($file, ZipArchive::OVERWRITE);
if ($res) {
// Add Streaming String
$zip->addFromString('file_name_within_archive.ext', $yourStringData);
// Add File
$zip->addFile('file_on_server.ext', 'second_file_name_within_archive.ext');
}
$zip->close();
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="file.zip"');
readfile($file);
unlink($file);
Categories: PHP
Tags: PHP
分類
Android
AngularJS
API Blueprint
Chrome
Cloud-Solution
Azure
Database
MySQL
DataStructure
Docker
Editor
Vim
Firefox
Git
GitLab
Google API
Hadoop
HTTP
Language
Go
Java
JavaScript
jQuery
jQueryChart
Node.js
Vue
Vue-CLI
PHP
Laravel
Lumen
ZendFramework
Python
Mac
Network
Cisco
DLink
Juniper
Oauth
Server
Apache
Share
Unix
FreeBSD
Linux
WebDesign
Bootstrap
CSS
HTML
Wordpress
Search
搜尋關鍵字:
寫了
5860316篇文章,獲得
23313次喜歡