2010-08-30 39 views

Trả lời

5

Sử dụng các chức năng zip_openzip_read để thực hiện. Documentation với nó bạn có thể tìm thấy ở http://pl2.php.net/manual/en/function.zip-read.php

<?php 
/** 
* This method unzips a directory within a zip-archive 
* 
* @author Florian 'x!sign.dll' Wolf 
* @license LGPL v2 or later 
* @link http://www.xsigndll.de 
* @link http://www.clansuite.com 
*/ 

function extractZip($zipFile = '', $dirFromZip = '') 
{ 
    define(DIRECTORY_SEPARATOR, '/'); 

    $zipDir = getcwd() . DIRECTORY_SEPARATOR; 
    $zip = zip_open($zipDir.$zipFile); 

    if ($zip) 
    { 
     while ($zip_entry = zip_read($zip)) 
     { 
      $completePath = $zipDir . dirname(zip_entry_name($zip_entry)); 
      $completeName = $zipDir . zip_entry_name($zip_entry); 

      // Walk through path to create non existing directories 
      // This won't apply to empty directories ! They are created further below 
      if(!file_exists($completePath) && preg_match('#^' . $dirFromZip .'.*#', dirname(zip_entry_name($zip_entry)))) 
      { 
       $tmp = ''; 
       foreach(explode('/',$completePath) AS $k) 
       { 
        $tmp .= $k.'/'; 
        if(!file_exists($tmp)) 
        { 
         @mkdir($tmp, 0777); 
        } 
       } 
      } 

      if (zip_entry_open($zip, $zip_entry, "r")) 
      { 
       if(preg_match('#^' . $dirFromZip .'.*#', dirname(zip_entry_name($zip_entry)))) 
       { 
        if ($fd = @fopen($completeName, 'w+')) 
        { 
         fwrite($fd, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry))); 
         fclose($fd); 
        } 
        else 
        { 
         // We think this was an empty directory 
         mkdir($completeName, 0777); 
        } 
        zip_entry_close($zip_entry); 
       } 
      } 
     } 
     zip_close($zip); 
    } 
    return true; 
} 

// The call to exctract a path within the zip file 
extractZip('clansuite.zip', 'core/filters'); 
?> 
+0

'nếu ($ zip)' không làm việc, bạn nên sử dụng 'nếu (is_resource ($ zip))'. Xem ['zip_open'] (http://php.net/manual/fr/function.zip-open.php). Ngoài ra, liên kết được cung cấp trong câu trả lời không còn nữa. – kjaquier

0

Giao thức zip:// được cung cấp bởi ZIP extension của PHP. Kiểm tra đầu ra phpinfo() của bạn xem tiện ích có được cài đặt hay không.

+0

từ phpinfo(): Zip => kích hoạt Version Extension => $ Id: php_zip.c, v 1.1.2.38 2007/08/06 22:02:32 bjori Exp $ Zip phiên bản => 2.0. 0 Phiên bản Libzip => 0.7.1 Dòng PHP đã đăng ký => zip, php, tệp, dữ liệu, http, ftp, compress.bzip2, compress.zlib, https, ftps – Sam

+0

Bạn đã kiểm tra xem tệp bạn có cố gắng mở thực sự là một tệp '.zip' hợp lệ? – joschi

+0

%> tệp test.zip test.zip: Dữ liệu lưu trữ zip, ít nhất là v2.0 để trích xuất – Sam

0

sử dụng ZipArchive lớp

$zip = new ZipArchive; 
$zip->open('test.zip'); 
echo $zip->getFromName('filename.txt'); 
$zip->close(); 
Các vấn đề liên quan