PHP/ThinkPHP实现批量打包下载文件的方法示例

yipeiwu_com5年前PHP代码库

前言

本文主要给大家介绍的是关于PHP/ThinkPHP实现批量打包下载文件的相关内容,分享出来供大家参考学习,话不多说了,来一起看看详细的介绍:

需求描述:

有数个文件,包含图片,文档。需要根据条件自动打包成压缩包,提供下载。

解决(ZipArchive 类):

PHP提供了ZipArchive 类可为我们实现这一功能,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);

区别在引用的时候路径要对,结束。

相关参考:

http://www.php.net/manual/zh/class.ziparchive.php

http://dengrongguan12.github.io/blog/2016/php-ziparchive/

总结

好了,大概就这样,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【宜配屋www.yipeiwu.com】的支持

相关文章

php查看网页源代码的方法

本文实例讲述了php查看网页源代码的方法。分享给大家供大家参考。具体实现方法如下: <?php $url = "//www.jb51.net"; $fp = @fope...

php实现比较全的数据库操作类

本文实例讲述了php实现比较全的数据库操作类。分享给大家供大家参考。具体如下: <?php class database { private $hostname...

PHP添加Xdebug扩展的方法

xdegug是一个很好的php调试扩展,安装方法也很简单,基本和其他的扩展安装方式差不多. 一、下载对应的DLL 下载地址:https://xdebug.org/download.php...

PHP 使用header函数设置HTTP头的示例解析 表头

如下所示:复制代码 代码如下://定义编码  header( 'Content-Type:text/html;charset=utf-8 ');  //Atom&nb...

详解PHP版本兼容之openssl调用参数

背景与问题解决方式 老项目重构支付宝部分代码整合支付宝新的sdk时发现验签总是失败,才发现是open_verify最后的参数传输问题。而open_sign同样如此。本文主要说明open_...