在 PHP 7.4 中解压缩 ZIP 文件
1、参考:https://www.php.net/manual/zh/ziparchive.extractto.php 。ZipArchive::extractTo。将压缩文件解压缩到指定的目录。如图1
1 2 3 4 5 6 7 8 9 10 | <?php $zip = new ZipArchive; if ( $zip ->open( 'test.zip' ) === TRUE) { $zip ->extractTo( '/my/destination/dir/' ); $zip ->close(); echo 'ok' ; } else { echo 'failed' ; } ?> |
2、最终参考实现如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | // 解压缩至的本地目标路径 $destination = storage_path( 'app' ) . $directory . '/' . microtime(true) . '.' . mt_rand(); $absolutePath = $destination . '.zip' ; app(ZipHandler:: class )->unzip( $destination , $absolutePath ); /** * 解压缩 ZIP * @param string $destination 解压缩至的本地目标路径 * @param string $entrie 待解压缩的文件的绝对路径 * @return void */ public function unzip( $destination , $entrie ) { $zip = new \ZipArchive; if ( $zip ->open( $entrie ) === TRUE) { $zip ->extractTo( $destination ); $zip ->close(); } else { abort(500, 'Unzip failed.' ); } } |
3、解压缩后的目录结构,与原始文件名平级且同名。如图2
近期评论