php 批量下载pdf文件大小,PHP中通过ZipArchive批量下载pdf文件

PHP中通过ZipArchive批量下载pdf文件

场景

通过点击一个按钮批量下载远程pdf文件

步骤

1.获取远程文件内容,写入临时目录和文件

2.将临时目录打包

3.下载打包文件

4.下载后删除临时文件

代码部分

//文件地址

$file_path = [

‘http://localhost:8888/1.pdf‘,

‘http://localhost:8888/2.pdf‘,

‘http://localhost:8888/3.pdf‘,

‘http://localhost:8888/4.pdf‘,

];

//利用ZipArchive实现打包

$zip = new \ZipArchive();

$zip_path = ‘./temp/‘;

$zip_name = ‘temp.zip‘;

$zip_file = $zip_path . $zip_name;

if ($zip->open($zip_file, \ZipArchive::CREATE)) {

foreach($file_path as $v) {

//获取文件内容

$file_content = file_get_contents($v);

//写入临时文件(没有temp目录的需要先手动创建或用mkdir创建)

$temp_file_path = $zip_path . ‘temp_‘ . time() . rand(1000, 9999) . ‘.pdf‘;

//创建临时目录

if (!is_dir($zip_path)) {

if ((mkdir($zip_path, 0777, true)) === false) {

return ‘临时目录创建失败!‘;

}

}

//写入文件

$temp_file = file_put_contents($temp_file_path, $file_content);

if (!$temp_file) {

continue;

}

//文件写入zip中

$zip->addFile($temp_file_path);

}

//关闭

$zip->close();

}

//设置下载zip的头信息

header(‘Content-Type: application/zip‘); //zip压缩文件

header("Content-Transfer-Encoding: Binary"); //二进制传输

header("Content-Type:application/force-download"); //强制下载

header("Content-Disposition: attachment; filename=" . $zip_name); //告诉浏览器下载并设置文件名

readfile($zip_file);

//下载后删除临时目录(delete_dir方法见下方)

if (is_dir($zip_path)) delete_dir($zip_path);

/**

* 删除目录

*/

if (!function_exists(‘delete_dir‘)) {

function delete_dir($path)

{

if (!is_dir($path)) {

return false;

}

$dirs = scandir($path);

foreach ($dirs as $dir) {

if ($dir == ‘.‘ || $dir == ‘..‘) {

continue;

}

if (is_dir($path . $dir)) {

delete_dir($path . $dir);

} else {

@unlink($path . $dir);

}

}

@rmdir($path);

}

}

参考

原文:https://www.cnblogs.com/trblog/p/12812531.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值