您的位置:首页 > 编程语言 > PHP开发

php使用 ZipArchive 压缩文件并提供下载

2013-01-05 16:57 633 查看
ZipArchive 如何使用:

new一个ZipArchive对象,然后使用open方法创建一个zip文件,接着使用addFile方法,将要打包的文件写入刚刚创建的zip文件中,关闭该对象。

使用open方法的时候,第二个参数$flags是可选的,$flags用来指定对打开的zip文件的处理方式,共有四种情况

ZIPARCHIVE::OVERWRITE 总是创建一个新的文件,如果指定的zip文件存在,则会覆盖掉

ZIPARCHIVE::CREATE 如果指定的zip文件不存在,则新建一个

ZIPARCHIVE::EXCL 如果指定的zip文件存在,则会报错

ZIPARCHIVE::CHECKCONS

ZipArchive 代码实现:

$filename = "/usr/local/temp/".mb_convert_encoding($fileShowName,'gbk','utf-8')."_".substr($fileList[0], 8,8).".zip"; //最终生成的 文件名(含路径)
//生成文件
$zip = new ZipArchive();//使用本 类,linux需开启 zlib,windows需取消php_zip.dll前的注释
if ($zip->open($filename, ZIPARCHIVE::OVERWRITE )!==TRUE) {
exit('无法打开文件,或 者文件创建失败');
}
foreach( $fileList as $val){
$msg=str_replace(".voc", ".mp3", $val);
$filePath="uservoice/Tweets/qqnew/".substr($msg, 8,8);
$filePath=$filePath."/".$msg;
if(file_exists($filePath)){
$zip->addFile( $filePath ,$msg);//第二个参 数是放在压缩包中的文件名称,如果文件可能会有重复,就需要注意一下
}
}
$zip->close();//关闭
if( !file_exists($filename)){
exit("无法找到文件"); //即使创建,仍有可能失败。。。。
}
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename)); //文件名
header("Content-Type: application/zip"); //zip格式的
header("Content-Transfer-Encoding: binary");    //告诉浏览 器,这是二进制文件
header('Content-Length: '. filesize($filename));    //告诉浏览 器,文件大小
@readfile($filename);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: