PHP zip ZipArchive 扩展

文章介绍了如何在PHP中利用ZipArchive类创建Zip文件,包括添加文件和从当前目录提取文件。还展示了如何获取ZIP文件内所有成员文件的信息以及如何解压缩ZIP文件到指定目录。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[在 PHP 中使用 ZipArchive() 类创建 Zip 文件]

ZipArchive() 是用于在 PHP 中执行 ZIP 操作的类。使用 ZipArchive() 类,创建一个 Zip 文件。

<?php
$create_zip = new ZipArchive();
$file_name = "./New.zip";

if ($create_zip->open($file_name, ZipArchive::CREATE)!==TRUE) {
    exit("cannot open the zip file <$file_name>\n");
}
$current_dir=getcwd();
//Create files to add to the zip
$create_zip->addFromString("file1 ". time().".txt" , "#1 This is This is the test file number one.\n"); 
$create_zip->addFromString("file2 ". time().".txt", "#2 This is This is the test file number one.\n");
//add files to the zip
$create_zip->addFile($current_dir . "/too.php","/testfromfile.php");
echo "Number of files added: " . $create_zip->numFiles;
echo "<br>";
echo "Failed to add:" . $create_zip->status ;
$create_zip->close();
?>

上面的代码创建了两个包含一些内容的文本文件,并将它们添加到一个 zip 文件中。

输出:

在 PHP 中创建 Zip 文件

在 PHP 中使用 ZipArchive() 类创建 Zip 文件

让我们使用 PHP 的 ZipArchive() 类提取在第一个代码中创建的 zip 文件。

<?php
$extract_zip = new ZipArchive;
$open_zip = $extract_zip->open('New.zip');
if ($open_zip === TRUE) {
	$extract_to = getcwd();
    $extract_zip->extractTo($extract_to); //extract to the current working directory.
    echo "Number of Files to be Extracted:" . $extract_zip->numFiles . "<br>";
	$extract_zip->close();
    echo 'Files Successfully Extracted!';
} 
else {
    echo 'Cannot Extract!';
}
?>

上面的代码将提取在第一个示例中创建的 New.zip 文件。

输出:

在 PHP 中提取 Zip 文件

如何使用 PHP Zip 扩展来获取 ZIP 的所有成员文件的信息

PHP ZIP 扩展可以获取 ZIP 内所有文件的信息。

<?php
$zip_file = zip_open("New.zip");
if ($zip_file) {
    while ($zip_members = zip_read($zip_file)) {
        echo "Name of the file:               " . zip_entry_name($zip_members) . "<br>";
        echo "Original Size of the File:    " . zip_entry_filesize($zip_members) . "<br>";
        echo "Compressed Size of the File:    " . zip_entry_compressedsize($zip_members) . "<br>";
        echo "Method of Compression: " . zip_entry_compressionmethod($zip_members) . "<br>";

        if (zip_entry_open($zip_file, $zip_members, "r")) {
            echo "Content of the file:<br>";
            $buf = zip_entry_read($zip_members, zip_entry_filesize($zip_members));
            echo "$buf <br>";

            zip_entry_close($zip_members);
        }
        echo "<br>";
    }
    zip_close($zip_file);
}
?>

上面的代码使用内置的 ZIP 函数来获取 ZIP 内的文件信息。

输出:

Name of the file: file1 1644842283.txt
Original Size of the File: 45
Compressed Size of the File: 39
Method of Compression: deflated
Content of the file:
#1 This is test file number one.

Name of the file: file2 1644842283.txt
Original Size of the File: 45
Compressed Size of the File: 39
Method of Compression: deflated
Content of the file:
#2 This is test file number two.

[使用 PHP 创建一个 Zip 文件]

下面的示例代码将创建一个 zip 文件 tutorial.zip,并添加文件。

在我们的 htdocs 目录中,我们有 Files to zip 文件夹,其中包含两个文件。我们将压缩目录 Files to zip

<?php
// Enter the name of directory
$pathdir = "Files to zip/";

//Create a name for the zip folder
$zipcreated = "Files to zip.zip";

// Create new zip class
$zip = new ZipArchive;

if($zip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) {

    // Store the files in our `Files to zip` zip file.
    $dir = opendir($pathdir);

    while($file = readdir($dir)) {
        if(is_file($pathdir.$file)) {
            $zip -> addFile($pathdir.$file, $file);
}
}
}
?>

此代码在我们的根目录中创建一个新的 zip,Files to zip,如下所示。

压缩图像的文件

我们使用目录 Files to zip 创建 zip 文件夹 Files to zip。我们的目录有两个文件,insert.phpLoader.php

我们应该在我们的 zip 文件夹中找到上述文件。让我们来看看。

zip 文件里面

[使用 PHP 解压缩 Zip 文件]

让我们看看如何使用 PHP 解压缩 zip 文件。

例子:

<?php
// Create new zip class
$zip = new ZipArchive;

// Add zip filename which needs to unzip

$zip->open('Files to zip.zip');

// Extracts to current directory
$zip->extractTo('./Files to zip');

$zip->close();
?>

输出:

解压压缩文件

我们使用代码将 Files to zip.zip 解压缩到 Files to zip 文件夹。

### PHPZipArchive 扩展的用法 #### 安装与配置 为了使用 `ZipArchive` 类,在大多数情况下需要确保已安装并启用了相应的 PHP 扩展。对于 Linux 用户而言,可以通过包管理器来完成这项工作;而对于 Windows 用户,则需确认 php.ini 文件里有正确的设置[^1]。 - **Linux (Debian/Ubuntu)**: ```bash sudo apt-get install php-zip ``` - **Windows**: 编辑 `php.ini` 文件取消注释如下行: ```ini extension=php_zip.dll ``` 重启 Web 服务器使更改生效。 #### 创建 ZIP 归档 一旦环境准备就绪,就可以利用 `ZipArchive::create()` 方法或者构造函数实例化一个新的 `ZipArchive` 对象,并通过调用成员函数如 `addFile()` 或者 `addFromString()` 来向其中添加文件或字符串内容[^2]。 ```php <?php $zip = new \ZipArchive(); if ($zip->open('test.zip', \ZipArchive::CREATE) === TRUE) { $zip->addFile('/path/to/index.php', 'newname.php'); $zip->close(); } else { echo 'Failed to create archive'; } ?> ``` 上述代码展示了怎样创建名为 test.zip 的新存档并将指定路径下的 index.php 添加进去同时重命名为 newname.php。 #### 解压 ZIP 文件 解压缩操作同样简单明了,只需打开现有的 .zip 文件并通过 `extractTo()` 函数指定期望的目标目录即可。 ```php <?php $zip = new \ZipArchive; $res = $zip->open('game.zip'); if ($res === TRUE) { $zip->extractTo('/my/game/dir/'); $zip->close(); echo 'ok'; } else { echo 'failed, code:' . $res; } ?> ``` 这段脚本会尝试打开 game.zip 并将其全部内容提取到 /my/game/dir/ 下面去。 #### 访问 ZIP 内部结构而不必先解压 除了基本的打包和拆包功能外,还可以借助于 `getFromName()` 和其他类似的 API 获取特定项的内容而无需实际展开整个档案[^3]。 ```php <?php $zip = new \ZipArchive; if ($zip->open('game.zip') === TRUE) { $content = $zip->getFromName('readme.txt'); var_dump($content); $zip->close(); } else { echo '无法打开ZIP文件'; } ?> ``` 此片段演示了如何直接读取 readme.txt 的文本内容而不是把它单独拿出来保存成物理文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小柴没吃饱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值