PHP 解压 ZIP 压缩包,解决多级中文乱码问题
测试环境windows10
正常的zip解压在网上百度都能找到
一、 不考虑乱码等问题
$zip = new ipArchive; $zipfile = “./test.zip”; $res = z i p − > o p e n ( zip->open( zip−>open(zipfile); $s = $zip->extractTo(‘解压保存目录’)
二、解决中文乱码
KaTeX parse error: Undefined control sequence: ipArchive at position 11: zip = new ̲Z̲i̲p̲A̲r̲c̲h̲i̲v̲e̲(); if (zip->open(KaTeX parse error: Expected }, got EOF at end of input: … if(!is_dir(path)){ mkdir($path, 0777, true); } // 获取解压的文件数组 $fileNum = $zip->numFiles;
for ($i = 0; $i < $fileNum; $i++) { // 处理每一个文件 $statInfo = $zip->statIndex($i, ipArchive::FL_ENC_RAW); // 获取文件的名称的编码格式 $encoding = mb_detect_encoding($statInfo[name], [UTF-8,GBK,BIG5,CP936]); // 转换成UTF-8编码 if (DIRECTORY_SEPARATOR == /){ //linux $filename = iconv($encoding, UTF-8, $statInfo[name]); }else{ //win $filename = iconv($encoding, UTF-8, $statInfo[name]); } if($statInfo[crc] == 0) { //新建目录 //mkdir($path./.substr($filename, 0,-1)); mkdir($path, 0777, true); } else { if(!copy(zip:// . $filePath . # . $zip->getNameIndex($i), $path . / . $filename)){ return false; } } } $zip->close(); return true;
} else { return false; }
三、对比二只加了一段代码
KaTeX parse error: Undefined control sequence: ipArchive at position 11: zip = new ̲Z̲i̲p̲A̲r̲c̲h̲i̲v̲e̲(); if (zip->open(KaTeX parse error: Expected }, got EOF at end of input: … if(!is_dir(path)){ mkdir($path, 0777, true); } // 获取解压的文件数组 $fileNum = $zip->numFiles;
for ($i = 0; $i < $fileNum; $i++) { // 处理每一个文件 $statInfo = $zip->statIndex($i, ipArchive::FL_ENC_RAW); // 获取文件的名称的编码格式 $encoding = mb_detect_encoding($statInfo[name], [UTF-8,GBK,BIG5,CP936]); // 转换成UTF-8编码 if (DIRECTORY_SEPARATOR == /){ //linux $filename = iconv($encoding, UTF-8, $statInfo[name]); }else{ //win $filename = iconv($encoding, UTF-8, $statInfo[name]); } if($statInfo[crc] == 0) { //新建目录 //mkdir($path./.substr($filename, 0,-1)); mkdir($path, 0777, true); } else { if(strpos($filename,/) !== false){ //获取文件名(看自己需求) $mkdFile = explode(/,$filename); if(count($mkdFile) == 1){ $namePath = $mkdFile[0]; }else{ $namePath = $mkdFile[count($mkdFile)-1]; } //获取zip单个文件数据 $fp = fopen(zip:// . $filePath . # . $zip->getNameIndex($i), rb); while (!feof($fp)) { //fread 获取文件数据流 保存到本地 file_put_contents($path.DIRECTORY_SEPARATOR.$namePath, fread($fp,9999999)); } }else{ if(!copy(zip:// . $filePath . # . $zip->getNameIndex($i), $path . / . $filename)){ return false; } } } } $zip->close(); return true;
} else { return false; }
四、总结
以上亲测有效,根据自己逻辑进行调整