以PHP格式读取zip文件的最佳方法
使用zip_open
和zip_read
函数来做到这一点。 文件,从而你可以找到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');
?>
的zip://
协议是由PHP的ZIP extension提供。检查您的phpinfo()
输出是否已安装扩展。
从phpinfo()函数: 邮编=>启用 扩展版本=> $编号:php_zip.c,V 1.1.2.38 2007年8月6日22时02分32秒bjori精通$ 邮编版本=> 2.0。 0 Libzip version => 0.7.1 已注册PHP Streams => zip,php,file,data,http,ftp,compress.bzip2,compress.zlib,https,ftps – Sam 2010-08-30 09:22:45
您是否检查过您尝试的文件open实际上是一个有效的'.zip'文件? – joschi 2010-08-30 11:14:48
%> file test.zip test.zip:Zip档案数据,至少要提取v2.0 – Sam 2010-09-09 09:26:13
使用ZipArchive
类
$zip = new ZipArchive;
$zip->open('test.zip');
echo $zip->getFromName('filename.txt');
$zip->close();
'如果($ ZIP)'不工作,你应该使用'如果(is_resource($ ZIP))'。参见['zip_open'](http://php.net/manual/fr/function.zip-open.php)。此外,答案中提供的链接不再可用。 – kjaquier 2017-01-16 11:28:38