2013-03-20 7 views
1

я использую следующие для архивированияАрхивирование без включать текущий каталог

//http://ninad.pundaliks.in/blog/2011/05/recursively-zip-a-directory-with-php/ 

class FlxZipArchive extends ZipArchive { 

    public function addDir($location, $name) { 
     $this->addEmptyDir($name);  
     $this->addDirDo($location, $name); 
    } // EO addDir 

    private function addDirDo($location, $name) { 
     $name .= '/'; 
     $location .= '/'; 

     // Read all Files in Dir 
     $dir = opendir ($location); 
     while ($file = readdir($dir)) 
     { 
      if ($file == '.' || $file == '..') continue; 

      // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File(); 
      $do = (filetype($location . $file) == 'dir') ? 'addDir' : 'addFile'; 
      $this->$do($location . $file, $name . $file); 
     } 
    } // EO addDirDo(); 
} 


function zipIt($source, $target){ 
    $za = new FlxZipArchive; 

    $res = $za->open($target, ZipArchive::CREATE); 

    if($res === TRUE) { 
     $za->addDir($source, basename($source)); 
     $za->close(); 
    } 
    else 
     echo 'Could not create a zip archive'; 

} 

$the_folder = './Sales report'; 
$zip_file_name = './Sales report.docx'; 
//Don't forget to remove the trailing slash in folder 
zipIt($the_folder,$zip_file_name,false); 

Проблема заключается в том, что она включает в себя текущий каталог,

Sales report/ 
    file1.html 
    file2.html 
    Sub_Dir/ 
     file19.html 

Но я просто хочу

file1.html 
    file2.html 
    Sub_Dir/ 
     file19.html 

Как сделать это?

ответ

1

Вот что я использую:

/** 
* Add a directory and its contents to the archive 
* 
* @param string $dir  The local filesystem path to the directory 
* @param string $localName The archive filesystem path to the directory 
* 
* @throws \RuntimeException When adding an object to the archive fails 
*/ 
public function addDir($dirPath, $localName = NULL) 
{ 
    if ($localName === NULL) { 
     $localName = basename($dirPath); 
    } 
    if (!$this->addEmptyDir($localName)) { 
     throw new \RuntimeException('Error adding directory '.$dirPath.' to archive'); 
    } 

    $this->addDirContents($dirPath, $localName); 
} 

/** 
* Add the contents of a directory to the archive 
* 
* @param string $dir  The local filesystem path to the directory 
* @param string $localName The archive filesystem path to the directory 
* 
* @throws \RuntimeException When adding an object to the archive fails 
*/ 
public function addDirContents($dirPath, $localName = '') 
{ 
    $base = ltrim($localName.'/', '/'); 

    foreach (glob("$dirPath/*") as $file) { 
     if (is_dir($file)) { 
      $this->addDir($file, $base.basename($file)); 
     } else { 
      if (!$this->addFile($file, $base.basename($file))) { 
       throw new \RuntimeException('Error adding file '.$file.' to archive'); 
      } 
     } 
    } 
} 

Как ваш код, эти методы принадлежат классу, который простирается \ZipArchive. addDir() добавляет каталог и его содержимое, addDirContents() просто добавляет содержимое без создания родительского каталога в архиве (и, следовательно, делает то, что вы хотите).

Мне обычно не нравится просто выдавать бесплатный рабочий код без объяснений, но это просто так. У меня есть именно то, что вам нужно открыть в моем редакторе.

+0

но мне нужен подкаталог быть включено, как в примере Sub_Dir включен, делает ваш код поддерживает это? – william007

+0

@ william007 Да, это так, оно рекурсивно добавляет содержимое каталога в архив. Если вы вызываете 'addDir()', вы получите свой первый пример макета, если вы вызываете 'addDirContents()', вы получите второй (желаемый) макет – DaveRandom

0

Я использую этот код, наконец, предоставить возможность выбора или не включать текущий каталог:

<?php 
//http://ninad.pundaliks.in/blog/2011/05/recursively-zip-a-directory-with-php/ 



class FlxZipArchive extends ZipArchive { 

    public function addDir1($location, $name, $includeCurrDir) { 
     if($includeCurrDir) 
     $this->addEmptyDir($name);  
     $this->addDirDo1($location, $name, $includeCurrDir); 
    } // EO addDir 

    private function addDirDo1($location, $name, $includeCurrDir) { 
     if($includeCurrDir) 
     $name .= '/'; 
     else 
     $name = ''; 

     $location .= '/'; 

     // Read all Files in Dir 
     $dir = opendir ($location); 
     while ($file = readdir($dir)) 
     { 
      if ($file == '.' || $file == '..') continue; 

      // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File(); 
      $do = (filetype($location . $file) == 'dir') ? 'addDir' : 'addFile'; 
      $this->$do($location . $file, $name . $file); 
     } 
    } // EO addDirDo(); 

    public function addDir($location, $name) { 
     $this->addEmptyDir($name);  
     $this->addDirDo($location, $name); 
    } // EO addDir 

    private function addDirDo($location, $name) { 
     $name .= '/'; 
     $location .= '/'; 

     // Read all Files in Dir 
     $dir = opendir ($location); 
     while ($file = readdir($dir)) 
     { 
      if ($file == '.' || $file == '..') continue; 

      // Rekursiv, If dir: FlxZipArchive::addDir(), else ::File(); 
      $do = (filetype($location . $file) == 'dir') ? 'addDir' : 'addFile'; 
      $this->$do($location . $file, $name . $file); 
     } 
    } // EO addDirDo(); 
} 


function zipIt($source, $target, $includeCurrDir){ 
    $za = new FlxZipArchive; 

    $res = $za->open($target, ZipArchive::CREATE); 

    if($res === TRUE) { 
     $za->addDir1($source, basename($source),$includeCurrDir); 
     $za->close(); 
    } 
    else 
     echo 'Could not create a zip archive'; 

} 
$the_folder = 'Sales report'; 
$zip_file_name = 'Sales report.docx'; 
//Don't forget to remove the trailing slash in folder 
zipIt($the_folder,$zip_file_name,false); 


?> 
Смежные вопросы