PHP Doku:: Extrahiert den Archivinhalt - function.ziparchive-extractto.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzErweiterungen zur Datenkompression und ArchivierungZipThe ZipArchive classZipArchive::extractTo

Ein Service von Reinhard Neidl - Webprogrammierung.

The ZipArchive class

<<ZipArchive::deleteName

ZipArchive::getArchiveComment>>

ZipArchive::extractTo

(PHP 5 >= 5.2.0, PECL zip >= 1.1.0)

ZipArchive::extractToExtrahiert den Archivinhalt

Beschreibung

bool ZipArchive::extractTo ( string $destination [, mixed $entries ] )

Extrahiert das komplette Archiv oder die gegebenen Dateien in das angegebene Ziel.

Parameter-Liste

destination

Stelle, an die die Dateien extrahiert werden sollen.

entries

Die zu extrahierenden Einträge. Es wird entweder ein einzelner Eintragsname oder ein Array von Namen akzeptiert.

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben.

Beispiele

Dieses Beispiel öffnet ein ZIP-Dateiarchiv, liest jede Datei im Archiv und gibt ihren Inhalt aus. Das test2.zip-Archiv, das in diesem Beispiel verwendet wird, ist eines der Testarchive der ZZIPlib-Quelldistribution.

Beispiel #1 Alle Einträge extrahieren

<?php
$zip 
= new ZipArchive;
if (
$zip->open('test.zip') === TRUE) {
    
$zip->extractTo('/mein/ziel/verzeichnis/');
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'Fehler';
}
?>

Beispiel #2 Nur zwei Einträge extrahieren

<?php
$zip 
= new ZipArchive;
$res $zip->open('test_im.zip');
if (
$res === TRUE) {
    
$zip->extractTo('/mein/ziel/verzeichnis/', array('pear_item.gif''testfromfile.php'));
    
$zip->close();
    echo 
'ok';
} else {
    echo 
'Fehler';
}
?>

10 BenutzerBeiträge:
- Beiträge aktualisieren...
sachinyadav at live dot com
12.11.2010 9:29
This script will search for ".txt" file(any file name) inside test.zip archive. Suppose, 'example.txt' file is found then the script will copy 'example.txt' to "txt_files" directory and rename it to 'test.zip.txt' and will remove all the blank lines from 'test.zip.txt' and resave and will exit the loop without searching remaining entries.
This script can be useful to extract .DIZ and GIF files to display ZIP archive details in your script.
<?php
   $value
="test.zip";
  
$filename="zip_files/$value";
  
$zip = new ZipArchive;
     if (
$zip->open($filename) === true) {
      echo
"Generating TEXT file.";
          for(
$i = 0; $i < $zip->numFiles; $i++) {
            
$entry = $zip->getNameIndex($i);
               if(
preg_match('#\.(txt)$#i', $entry))
                {
               
////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
               
copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt');
               
$content = file_get_contents("txt_files/$value.txt");
               
$newcontent = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
               
file_put_contents("txt_files/$value.txt", "$newcontent");
                break;
                }
              } 
            
$zip->close();
            }
    else{
         echo
"ZIP archive failed";
        }
?>

enjoy PHP programming.
Sachin Yadav
php-dev at proneticas dot net
8.11.2010 8:22
If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder).

<?php

$path
= 'zipfile.zip'

$zip = new ZipArchive;
if (
$zip->open($path) === true) {
    for(
$i = 0; $i < $zip->numFiles; $i++) {
       
$filename = $zip->getNameIndex($i);
       
$fileinfo = pathinfo($filename);
       
copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']);
    }                  
   
$zip->close();                  
}

?>

* On a side note, you can also use $_FILES['userfile']['tmp_name'] as the $path for an uploaded ZIP so you never have to move it or extract a uploaded zip file.

Cheers!

ProNeticas Dev Team
quake2005 at gmail dot com
20.08.2010 20:05
If you want to extract one file at a time, you can use this:

<?php

$path
= 'zipfile.zip'

$zip = new ZipArchive;
if (
$zip->open($path) === true) {
                   
    for(
$i = 0; $i < $zip->numFiles; $i++) {
                        
       
$zip->extractTo('path/to/extraction/', array($zip->getNameIndex($i)));
                       
       
// here you can run a custom function for the particular extracted file
                       
   
}
                   
   
$zip->close();
                   
}

?>
cory dot mawhorter at ephective dot com
18.04.2010 22:28
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.]
Anonymous
3.12.2009 1:38
I am using this function to extract a specific folder and it's contents from a zip file:

<?php
function extractDir($zipfile, $path) {
  if (
file_exists($zipfile)) {
   
$files = array();
   
$zip = new ZipArchive;
    if (
$zip->open($zipfile) === TRUE) {
      for(
$i = 0; $i < $zip->numFiles; $i++) {
       
$entry = $zip->getNameIndex($i);
       
//Use strpos() to check if the entry name contains the directory we want to extract
       
if (strpos($entry, "/MyFolder/")) {
         
//Add the entry to our array if it in in our desired directory
         
$files[] = $entry;
        }
      }
     
//Feed $files array to extractTo() to get only the files we want
     
if ($zip->extractTo($path, $files) === TRUE) {
        return
TRUE;
      } else {
        return
FALSE;
      }
     
$zip->close();
    } else {
      return
FALSE;
    }
  } else {
    return
FALSE;
  }
}

//Run the function
if (extractDir($zipfile, $path)) {
 
$extracted = "YES! :-D";
} else {
 
$extracted = "NO! :*(";
}

echo
$extracted;
?>
kawzaki at yahoo dot com
1.06.2009 6:28
Please be aware of the fact that using this function has OVERWRITE true.

an old file will be overwritten if the achieve (zipped file) contains file matching the same old file name.

old files that has no match in the zip, will be kept as is.

hopefully the someone will explain how to avoid overwriting old files.
Anonymous
2.04.2009 23:50
I found it useful to add this to a function.

<?php
/**
*  Extracts a ZIP archive to the specified extract path
*
*  @param string $file The ZIP archive to extract (including the path)   
*  @param string $extractPath The path to extract the ZIP archive to
*
*  @return boolean TURE if the ZIP archive is successfully extracted, FALSE if there was an errror

*/
function zip_extract($file, $extractPath) {

   
$zip = new ZipArchive;
   
$res = $zip->open($file);
    if (
$res === TRUE) {
       
$zip->extractTo($extractPath);
       
$zip->close();
        return
TRUE;
    } else {
        return
FALSE;
    }

}
// end function
?>
Kaya
3.10.2008 10:36
Make attention when using this function with apache & windows system. Windows file system use \  (backslash) instead of unix / (slash)
Use str_replace like this.
<?php
$zip
= new ZipArchive;
    if (
$zip->open("file.zip")){
       
$path = getcwd() . "/dirToextract/";
       
$path = str_replace("\\","/",$path);
        echo
$path;
        echo
$zip->extractTo($path);
       
$zip->close();
        echo
'Done.';
    } else {
        echo
"Error";
    }
?>
tBone
3.06.2008 2:03
This function, at least from my experience, maintains/forces the directory structure within the ZIP file.

ie. if you have FOLDER1/File1.txt in the zip file and you use
$zip->extractTo('/extract', 'FOLDER1/File1.txt');
the location of the extracted file will be:
/extract/FOLDER1/File1.txt
DerkaDerka
6.03.2007 7:48
This function will overwrite destination files with the same name.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)