file_get_contents("zip:///a/b/c.zip")
正在回归NULL
。如何在 PHP 5+ 中读取 zip 文件的解压内容?
使用
ZipArchive
类
$zip = new ZipArchive;
$zip->open('test.zip');
echo $zip->getFromName('filename.txt');
$zip->close();
使用
zip_open
和 zip_read
函数来完成此操作。
您可以在 http://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 函数: http://php.net/manual/en/book.zip.php
我知道这条消息很旧,但我遇到了同样的问题,我找到了 PHP 库的解决方案 ZipArchive。
所以我分享:)
// Initialization
$zipFilename = "example.zip";
// Object Creation
$zipObject = new ZipArchive();
// If File Open
if ($zipObject->open($zipFilename)===true)
{
// Getting Number of Files in ZIP
$nbFile = $zipObject->numFiles;
// For each file in ZIP
for ($i = 0; $i < $nbFile; $i++)
{
// Getting File Name
$filename = $zipObject->getNameIndex($i);
// Getting Content
$content = file_get_contents("zip://".$zipFilename."#".$filename);
// Display Infos
echo "<br /><b>".$filename."</b>";
echo "<br />".$content."<br />";
}
// End - For Each File in ZIP
// Close File
$zipObject->close();
}
// End - If File Open
我正在回答问题的第一部分,即使用 file_get_contents 方法 'file_get_contents("zip:///a/b/c.zip")' 通常该方法用于读取嵌套在 zip 文件中的一个特定文件。为了提取所有内容;其他人给出了很好的答案。
我在 Windows 上使用 PHP 7.2.34,后来在 Linux 上使用。我在 d:\data 保存了一个 zip 文件,此语法在 Windows 中有效。它确实回显了 ZIP 文件中“文件夹”内的 example1.py 的内容。
可能也与 zip 文件的创建位置/方式有关。当我从 PHP 中创建 zip 文件时,内部分隔符是反斜杠,但是当 Windows 创建 zip 文件时(通过使用 Windows 资源管理器中的“发送到压缩文件夹”功能),Windows 在 zip 文件中使用 Linux 约定!
此处需要进行更多测试,以了解 zip 文件中使用的是内部路径的分隔符
<?php
$str = file_get_contents('zip://d:/data/demo.zip#examples\\example1.py');
echo $str;
?>