php zip压缩资源下载

32F  2018/10/24 php



下面是一段实例,复制即可实现


// zip压缩包下载
function downloadQr(){
    $list = [
        ['img_url'=>'https://www.wailian.work/images/2018/10/15/_20181015110619.png','name'=>'firstfile'],
        ['img_url'=>'https://www.wailian.work/images/2018/10/15/_20181015112611.png','name'=>'secondfile'],
    ];
    //批量下载
    $tmpFile = tempnam('/tmp', 'tmp');    //创建一个临时文件 tempnam(dir,prefix)  dir(必需):目录  prefix(必需)。规定文件名的开头

    $zip = new ZipArchive;
    $zip->open($tmpFile, ZipArchive::CREATE);
    foreach ($list as $k=>&$v) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 0);
        curl_setopt($ch,CURLOPT_URL,$v['img_url']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $fileContent = curl_exec($ch);
        curl_close($ch);

        //string iconv ( string $in_charset , string $out_charset , string $str )  注:将字符串 str 从 in_charset 转换编码到 out_charset。
        $zip->addFromString(iconv('utf-8', 'gbk', $v['name'].'.png'), $fileContent);
    }

    $zip->close();

    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename=test.zip');
    header('Content-Length: ' . filesize($tmpFile));
    readfile($tmpFile);

    unlink($tmpFile);

}

downloadQr();

添加评论
全部回复
暂无回复