使用 PHP 讀取 ZIP 壓縮檔

做法

解壓縮

先解壓縮到指定目錄,再讀取檔案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php

require __DIR__.'/vendor/autoload.php';

$zipFilePath = './project.zip';
$extractPath = './';

$zip = new ZipArchive;

if ($zip->open($zipFilePath) === true) {
$zip->extractTo($extractPath);
$zip->close();
processFiles($extractPath);
}

function processFiles($dir) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
$filePath = "$dir/$file";
if (is_dir($filePath)) {
processFiles($filePath);
continue;
}
echo "$file\n";
}
}
}

串流

或使用串流的形式,直接讀取壓縮檔中的檔案。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php

require __DIR__.'/vendor/autoload.php';

$zipFilePath = './townhall.zip';

$zip = new ZipArchive;

if ($zip->open($zipFilePath) === true) {
$fileCount = $zip->numFiles;
processZipFiles($zip);
$zip->close();
}

function processZipFiles($zip, $folder = '') {
$fileCount = $zip->numFiles;

for ($i = 0; $i < $fileCount; $i++) {
$fileName = $zip->getNameIndex($i);

if (strpos($fileName, $folder) === 0 && $fileName !== $folder) {
$fileInfo = $zip->statIndex($i);
if (strpos($fileName, '/.') !== false) {
continue;
}
if ($fileInfo['size'] == 0 && substr($fileName, -1) === '/') {
processZipFiles($zip, $fileName . '/');
continue;
}
$fileStream = $zip->getStream($fileName);
if ($fileStream !== false) {
$fileContent = stream_get_contents($fileStream);
echo "File: $fileName\n";
echo "Content:\n$fileContent\n";
}
}
}
}