PHP Zip压缩导出图片,直接下载图片
1.需求,根据url导出图片
2.思路
准备好图片地址,想要保存的文件名称,在一个数组中
启动打开zip文件
下载文件添加到zip中
下载zip到本地
3.实现代码
第一种zip压缩导出图片,耗时较长,实现简单,
<?php
// 开始时间
$stime=microtime(true);
// 数据
$data="'Test04255','Test04254','Test04253','Test04252','Test04251','Test04250'";
//$data=file_get_contents(dirname(__FILE__).'/kuhao.txt');
//连接数据库
$pdo = new PDO("mysql:host=127.0.0.1;dbname=dbname","root","root");
$sql="SELECT `image`,`library_number`,`carousel_image`,`detail` FROM `art_info` WHERE `library_number` IN ({$data})";
$cx=$pdo ->query($sql,$pdo::FETCH_ASSOC);
$list=$cx->fetchAll($pdo::FETCH_ASSOC);
//文件路径
$tmpDir = $_SERVER['DOCUMENT_ROOT'].'\\'.'downimg\\';
if (!file_exists($tmpDir)) {
//创建文件夹
mkdir($tmpDir, 0777, true);
}
// 定义文件信息
$zipName='tupian.zip';
// 实例化zip类
$zip = new \ZipArchive();
$zipNameUrl = $tmpDir . $zipName;
if ($zip->open($zipNameUrl, \ZipArchive::OVERWRITE) !== true) {
//OVERWRITE 参数会覆写压缩包的文件 文件必须已经存在
if ($zip->open($zipNameUrl, \ZipArchive::CREATE) !== true) {
// 文件不存在则生成一个新的文件 用CREATE打开文件会追加内容至zip
return '下载失败,文件夹不存在';
}
}
// 循环保存图片信息
foreach ($list as $lis){
// 第一个默认的图
$picAllArr[] = ['fileurl'=>$lis['image'],'filename'=>$tmpDir.$lis['library_number'].'\image.'.pathinfo($lis['image'])['extension'],'dirname'=>$lis['library_number']];
$zip->addEmptyDir($lis['library_number']);
// 多图
$lis['carousel_image_arr'] = array_filter(explode(',', $lis['carousel_image']));
foreach ($lis['carousel_image_arr'] as $key => $imagear){
$ext = pathinfo($imagear)['extension'];
$picAllArr[] = ['fileurl'=>$imagear,'filename'=>$tmpDir.$lis['library_number'].'\carousel_image'.++$key.'.'.$ext,'dirname'=>$lis['library_number']];
}
// 详情图
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern,$lis['detail'],$match);
foreach ($match[1] as $key => $v){
$ext = pathinfo($v)['extension'];
$picAllArr[] = ['fileurl'=>$v,'filename'=>$tmpDir.$lis['library_number'].'\detail'.++$key.'.'.$ext,'dirname'=>$lis['library_number']];
}
}
// 开始时间
$yasuotusttime=microtime(true);
foreach ($picAllArr as $file) {
//判断图片是否存在
$isFile = checkFileExists($file['fileurl']);
if (!$isFile) {
continue;
}
//抓取图片内容
$fileContent = file_get_contents($file['fileurl']);
//添加图片到zip中
$zip->addFromString($file['dirname'].'\\'.basename($file['filename']), $fileContent);
}
// 结束时间
$yasuotuendtime=microtime(true);
$zip->close();
$etime=microtime(true);
$xiazaitime=$yasuotuendtime-$yasuotusttime;
$toime=$etime-$stime;
echo "当前页面执行时间为:{$toime}秒,下载时间{$xiazaitime}秒";
exit;
// 判断文件是哪里的,是否存在
function checkFileExists($file){
// 远程文件
if (strtolower(substr($file, 0, 5)) == 'https') {
// 远程文件
$header = get_headers($file, true);
return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
} elseif (strtolower(substr($file, 0, 4)) == 'http') {
// 远程文件
$header = get_headers($file, true);
return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
} else {
// 本地文件
return file_exists($file);
}
}
?>
第二种,耗时较短,使用缓存
//文件路径
$tmpDir = $_SERVER['DOCUMENT_ROOT'].'/'.'downimg/';
if (!file_exists($tmpDir)) {
//创建文件夹
mkdir($tmpDir, 0777, true);
}
// 循环保存图片信息
foreach ($list as $lis){
// 第一个默认的图
$picAllArr[] = ['fileurl'=>$lis['image'],'filename'=>$tmpDir.$lis['library_number'].'/image.'.pathinfo($lis['image'])['extension'],'dirname'=>$lis['library_number']];
//$zip->addEmptyDir($lis['library_number']);
if (!file_exists($tmpDir.$lis['library_number'])){
mkdir ($tmpDir.$lis['library_number'],0777,true);
}
// 多图
$lis['carousel_image_arr'] = array_filter(explode(',', $lis['carousel_image']));
foreach ($lis['carousel_image_arr'] as $key => $imagear){
$ext = pathinfo($imagear)['extension'];
$picAllArr[] = ['fileurl'=>$imagear,'filename'=>$tmpDir.$lis['library_number'].'/carousel_image'.++$key.'.'.$ext,'dirname'=>$lis['library_number']];
}
// 详情图
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern,$lis['detail'],$match);
foreach ($match[1] as $key => $v){
$ext = pathinfo($v)['extension'];
$picAllArr[] = ['fileurl'=>$v,'filename'=>$tmpDir.$lis['library_number'].'/detail'.++$key.'.'.$ext,'dirname'=>$lis['library_number']];
}
}
// 开始时间
$yasuotusttime=microtime(true);
foreach ($picAllArr as $file) {
//判断图片是否存在
$isFile = checkFileExists($file['fileurl']);
if (!$isFile) {
continue;
}
// 开启输出缓存区
ob_start();
readfile($file['fileurl']);
$img = ob_get_contents();
ob_end_clean();
//抓取图片内容
$myfile=fopen($file['filename'],'a');
fwrite($myfile,$img);
fclose($myfile);
//添加图片到zip中
}
// 结束时间
$yasuotuendtime=microtime(true);
$etime=microtime(true);
$xiazaitime=$yasuotuendtime-$yasuotusttime;
$toime=$etime-$stime;
echo "当前页面执行时间为:{$toime}秒,下载时间{$xiazaitime}秒";
exit;
// 判断文件是哪里的,是否存在
function checkFileExists($file){
// 远程文件
if (strtolower(substr($file, 0, 5)) == 'https') {
// 远程文件
$header = get_headers($file, true);
return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
} elseif (strtolower(substr($file, 0, 4)) == 'http') {
// 远程文件
$header = get_headers($file, true);
return isset($header[0]) && (strpos($header[0], '200') || strpos($header[0], '304'));
} else {
// 本地文件
return file_exists($file);
}
}
第三种,推荐,简洁方便
//文件路径
$tmpDir = './downimg/';
if (!file_exists($tmpDir)) {
//创建文件夹
mkdir($tmpDir, 0777, true);
}
// 开始时间
$yasuotusttime=microtime(true);
$imgcount=0;
// 循环保存图片信息
foreach ($list as $lis){
if (!file_exists($tmpDir.$lis['library_number'])){
mkdir ($tmpDir.$lis['library_number'],0777,true);
}
downimg($lis['image'],$tmpDir.$lis['library_number'].'/image.'.pathinfo($lis['image'])['extension'],$imgcount);
// 第一个默认的图
// 多图
$lis['carousel_image_arr'] = array_filter(explode(',', $lis['carousel_image']));
foreach ($lis['carousel_image_arr'] as $key => $imagear){
$ext = pathinfo($imagear)['extension'];
downimg($imagear,$tmpDir.$lis['library_number'].'/carousel_image'.++$key.'.'.$ext,$imgcount);
}
// 详情图
$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
preg_match_all($pattern,$lis['detail'],$match);
foreach ($match[1] as $key => $v){
$ext = pathinfo($v)['extension'];
downimg($v,$tmpDir.$lis['library_number'].'/detail'.++$key.'.'.$ext,$imgcount);
}
}
// 下载文件
function downimg($fileurl,$filename,&$imgcount){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$fileurl);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$data = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
if($code!=200){
return;
}
$file = fopen($filename,"a");
fwrite($file,$data); //写入文件
fclose($file);
$imgcount++;
}
// 结束时间
$yasuotuendtime=microtime(true);
$etime=microtime(true);
$xiazaitime=$yasuotuendtime-$yasuotusttime;
$toime=$etime-$stime;
echo "当前页面执行时间为:{$toime}秒,下载时间{$xiazaitime}秒,共{$imgcount}张图";
exit;