PHP/ThinkPHP實現(xiàn)批量打包下載文件的方法示例
前言
本文主要給大家介紹的是關(guān)于PHP/ThinkPHP實現(xiàn)批量打包下載文件的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),話不多說了,來一起看看詳細的介紹:
需求描述:
有數(shù)個文件,包含圖片,文檔。需要根據(jù)條件自動打包成壓縮包,提供下載。
解決(ZipArchive 類):
PHP提供了ZipArchive 類可為我們實現(xiàn)這一功能,demo:
<?php
$files = array('image.jpeg','text.txt','music.wav');
$zipname = 'enter_any_name_for_the_zipped_file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
///Then download the zipped file.
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>
ThinkPHP版
$zip = new \ZipArchive;
//壓縮文件名
$filename = 'download.zip';
//新建zip壓縮包
$zip->open($filename,\ZipArchive::OVERWRITE);
//把圖片一張一張加進去壓縮
foreach ($images as $key => $value) {
$zip->addFile($value);
}
//打包zip
$zip->close();
//可以直接重定向下載
header('Location:'.$filename);
//或者輸出下載
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename)); //文件名
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename)); //告訴瀏覽器,文件大小
readfile($filename);
區(qū)別在引用的時候路徑要對,結(jié)束。
相關(guān)參考:
http://www.php.net/manual/zh/class.ziparchive.php
http://dengrongguan12.github.io/blog/2016/php-ziparchive/
總結(jié)
好了,大概就這樣,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持
相關(guān)文章
ubuntu下編譯安裝xcache for php5.3 的具體操作步驟
本篇文章是對ubuntu下編譯安裝xcache for php5.3的操作進行了詳細的分析介紹,需要的朋友參考下2013-06-06
PHP操作MySQL的mysql_fetch_* 函數(shù)的常見用法教程
這篇文章主要介紹了PHP中操作MySQL的mysql_fetch函數(shù)的常見用法教程,文中提到了其下fetch_array和mysql_fetch_row以及mysql_fetch_object函數(shù)的使用,需要的朋友可以參考下2015-12-12
php 使用ActiveMQ發(fā)送消息,與處理消息操作示例
這篇文章主要介紹了php 使用ActiveMQ發(fā)送消息,與處理消息操作,結(jié)合實例形式分析了php使用ActiveMQ實現(xiàn)消息的發(fā)送與接收處理相關(guān)操作技巧,需要的朋友可以參考下2020-02-02

