note 97409 modified in function.ziparchive-extractto by danbrown

From: Date: Mon, 19 Apr 2010 14:08:04 +0000
Subject: note 97409 modified in function.ziparchive-extractto by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168408@lists.php.net to get a copy of this message
This function will flatten a zip file using the ZipArchive class. It will extract all the files in the zip and store them in a single destination directory. That is, no sub-directories will be created. If anyone knows a better way to determine if an entry is a directory, please chime in. I feel dirty checking for a trailing slash. <?php // dest shouldn't have a trailing slash function zip_flatten ( $zipfile, $dest='.' ) { $zip = new ZipArchive; if ( $zip->open( $zipfile ) ) { for ( $i=0; $i < $zip->numFiles; $i++ ) { $entry = $zip->getNameIndex($i); if ( substr( $entry, -1 ) == '/' ) continue; // skip directories $fp = $zip->getStream( $entry ); $ofp = fopen( $dest.'/'.basename($entry), 'w' ); if ( ! $fp ) throw new Exception('Unable to extract the file.'); while ( ! feof( $fp ) ) fwrite( $ofp, fread($fp, 8192) ); fclose($fp); fclose($ofp); } $zip->close(); } else return false; return $zip; } /* Example Usage: zip_flatten( 'test.zip', 'my/path' ); */ ?> [EDIT BY danbrown AT php DOT net: Added $zip-close() per indication by original poster in follow-up note on 18-APR-2010.] --was-- This function will flatten a zip file using the ZipArchive class. It will extract all the files in the zip and store them in a single destination directory. That is, no sub-directories will be created. If anyone knows a better way to determine if an entry is a directory, please chime in. I feel dirty checking for a trailing slash. <?php // dest shouldn't have a trailing slash function zip_flatten ( $zipfile, $dest='.' ) { $zip = new ZipArchive; if ( $zip->open( $zipfile ) ) { for ( $i=0; $i < $zip->numFiles; $i++ ) { $entry = $zip->getNameIndex($i); if ( substr( $entry, -1 ) == '/' ) continue; // skip directories $fp = $zip->getStream( $entry ); $ofp = fopen( $dest.'/'.basename($entry), 'w' ); if ( ! $fp ) throw new Exception('Unable to extract the file.'); while ( ! feof( $fp ) ) fwrite( $ofp, fread($fp, 8192) ); fclose($fp); fclose($ofp); } } else return false; return $zip; } /* Example Usage: zip_flatten( 'test.zip', 'my/path' ); */ ?> http://php.net/manual/en/function.ziparchive-extractto.php

« previous php.notes (#168408) next »