PHP(thinkphp6)将图片和文本转成文件并导出到压缩包

 1.准备条件:

        ZipArchive用来创建和操作压缩包的类

        RecursiveDirectoryIteratorRecursiveIteratorIterator 是 PHP 中用于递归遍历文件系统目录的类。

        这三个类都是内置的类,PHP5以上无需下载。

use ZipArchive; 
use RecursiveDirectoryIterator; 
use RecursiveIteratorIterator;

2.具体业务代码 。

    public static function export($ids){
        $idsArr = explode(',', $ids);
        $animeData = Db::name("op_anime")->field("id,title,coverpic")->whereIn('id', $idsArr)->select();
        $animeChapterData = Db::table("op_anime")->alias("a")
            ->join("op_anime_chapter b","a.id = b.anid")
            ->field("b.chaps,b.anid,b.info")
            ->whereIn('a.id', $idsArr)
            ->select();
        $animeData = $animeData->toArray();
        $animeChapterData = $animeChapterData->toArray();

        $rootPath = app()->getRootPath();
        // 1.创建一个临时目录来存放生成的image文件
        $tempDirImage = $rootPath."/"."download".'/image';
        if (!is_dir($tempDirImage)) {
            mkdir($tempDirImage, 0777, true);
        }
        //2.创建一个临时目录来存放生成的 TXT 文件
        $tempDirCoverpic = $rootPath."/"."download".'/coverpic';
        if (!is_dir($tempDirCoverpic)) {
            mkdir($tempDirCoverpic, 0777, true);
        }

        foreach ($animeData as $key => $val){
            if($val['coverpic'] != ""){
                // 遍历每个,生成对应的图片文件并添加到文件夹
                $imageData = @file_get_contents($val['coverpic']);
                $imageName = $tempDirImage . "/" . $val['title'] . ".jpg";
                file_put_contents($imageName, $imageData);
            }

            $fp = fopen($tempDirCoverpic."/" . $val['title'].".txt", 'a+');
            foreach ($animeChapterData as $key2 => $val2){
                if ($val2['anid'] == $val['id']){
                    if ($val2['chaps'] > 1) {
                        $content = html_entity_decode($val2['info']);
                    } else {
                        $content = html_entity_decode($val2['info']) . '<p>【此处为付费节点】</p>';
                    }
                    fwrite($fp, preg_replace("/(\&nbsp\;)/", " ", strip_tags(str_replace('</p>', "</p>\r\n", $content))));
                }
            }
            fclose($fp);
        }

        $rootPath = app()->getRootPath();
        // 1.创建一个临时目录来存放生成的image文件
        $folderPath = $rootPath."/"."download";
        $zipFileName = "download.zip";

        // 获取目录中的文件和子目录列表
        $files = array_diff(scandir($folderPath), array('..', '.'));
        // 如果文件列表为空,则目录就是空的
        if (!empty($files)) {
            self::createZipAndDownload($folderPath,$zipFileName); die;
        } else {
            return "没有正确内容可以导出。";
        }
    }


//$folderPath  文件夹路径
    //$zipFileName 压缩包文件名
    protected static function createZipAndDownload($folderPath, $zipFileName) {
        $zip = new ZipArchive;
        if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {

            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($folderPath),
                RecursiveIteratorIterator::SELF_FIRST
            );

            foreach ($files as $name => $file) {
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($folderPath));
                if (is_file($filePath)) {
                    // 将文件添加到压缩包中,并保留原有目录结构
                    $zip->addFile($filePath, $relativePath);
                } elseif (is_dir($filePath)) {
                    // 在压缩包中创建目录,并保留原有目录结构
                    $zip->addEmptyDir($relativePath);
                }
            }

            $zip->close();

            //删除目录下文件
            self::deleteFiles(app()->getRootPath()."/"."download".'/coverpic/');
            //删除目录下文件
            self::deleteFiles(app()->getRootPath()."/"."download".'/image/');

            // 设置响应头
//            $zipFileName = iconv("UTF-8", "GBK", $zipFileName);//加这行防止中文名字的文件乱码
            header('Content-Type: application/zip');
            header('Content-Disposition: attachment; filename="'.$zipFileName.'"');
            // 输出压缩包内容
            readfile($zipFileName);
//            // 删除临时文件
            unlink($zipFileName);
        } else {
            echo '无法创建压缩包';
        }
    }

    protected static function deleteFiles($dir)
    {
        if(!is_dir($dir)){
            return;
        }
        $handle = opendir($dir);
        while($file = readdir($handle)){
            if($file != "." && $file != ".."){
                $path = $dir ."/" . $file;
                if(is_file($path)){
                    unlink($path);
                }
                if(is_dir($path)){
                    self::deleteFiles($path);
                }
            }
        }
        closedir($handle);
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值