php函数大全txt下载,PHP打包下载多个TXT文件

此博客介绍了如何通过JavaScript获取前端页面上被选中的checkbox元素,将其ID转换为字符串并传递到PHP。PHP通过explode函数解析ID,实现章节下载功能。详细步骤包括获取用户选择、URL重定向、PHP接收参数及文件操作过程。
摘要由CSDN通过智能技术生成

前端用js获取页面选中的checkbox框,把ID写成字符串传递给PHP,PHP利用explode函数转成数组;已知文件路径

$(function(){

$("#download").click(function(){

//window.location.href="downzip.php?articleid=1&chapterids=1";

var articleid = $('#articleid').val();

var chapterids="";

$('input:checked').each(function(){

chapterids += $(this).attr('value')+',';

});

if(chapterids==""){

alert("请选择要下载的章节");

return false;

}

window.location.href="chapterdownload.php?articleid="+articleid+"&chapterids="+chapterids;

});

});

PHP代码:

$articleid = intval($_GET['articleid']);

$chapters = strval($_GET['chapterids']);

$chapterids = explode(',', $chapters);

for ($i=0;$i

$url = $_SERVER["DOCUMENT_ROOT"]."/files/article/txt/0/$articleid/$chapterids[$i].txt";

$datalist[$i] = $url;//获取文件路径数组

}

$datastr=date("d-H-i-s");

$filename = $_SERVER["DOCUMENT_ROOT"]."/files/article/downZip/".$datastr.".zip"; //最终生成的文件名(含路径)

if(!file_exists($filename)){

//重新生成文件

$zip = new ZipArchive();//使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释

if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {

exit('无法打开文件,或者文件创建失败');

}

foreach( $datalist as $val){

if(file_exists($val)){

$zip->addFile( $val, basename($val));//第二个参数是放在压缩包中的文件名称,如果文件可能会有重复,就需要注意一下

}

}

$zip->close();//关闭

}

if(!file_exists($filename)){

exit("无法找到文件"); //即使创建,仍有可能失败。。。。

}

$fp=fopen($filename,"r");

$file_size=filesize($filename);

//下载文件需要用到的头

Header("Content-type: application/octet-stream");

Header("Accept-Ranges: bytes");

Header("Accept-Length:".$filename);

Header("Content-Disposition: attachment; filename=".basename($filename));

$buffer=1024;

$file_count=0;

//向浏览器返回数据

while(!feof($fp) && $file_count

$file_con=fread($fp,$buffer);

$file_count+=$buffer;

echo $file_con;

}

fclose($fp);

unlink($datastr.'.zip'); //下载完成后要进行删除

本文由以下两个网址参考而来:

http://www.cnblogs.com/hongfei/archive/2012/06/12/2546881.html

http://www.lvtao.net/dev/php_zip.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值