📢 Webサイト閉鎖と移転のお知らせ
このWebサイトは2026年9月に閉鎖いたします。
新しい記事は移転先で追加しております。(旧サイトでは記事を追加しておりません)
概要
圧縮
ZIP形式
declare(strict_types=1);
namespace Utils;
use RuntimeException;
use ZipArchive;
use Generator;
/**
* ZIP形式で圧縮を行うメソッド
*
* @param string $sourcePath 圧縮対象のパス(ファイルまたはディレクトリ)
* @param string $destinationPath 出力先のZIPファイルパス
* @throws RuntimeException 圧縮処理中のエラー発生時
*/
function compressToZip(string $sourcePath, string $destinationPath): void
{
try {
$zip = new ZipArchive();
// ZIPファイルのオープン
if ($zip->open($destinationPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
throw new RuntimeException('ZIPファイルの作成に失敗しました');
}
// ディレクトリの場合は再帰的に処理
if (is_dir($sourcePath)) {
$files = $this->getFilesRecursively($sourcePath);
foreach ($files as $file) {
$relativePath = substr($file, strlen($sourcePath) + 1);
$zip->addFile($file, $relativePath);
}
}
else {
// 単一ファイルの場合
$zip->addFile($sourcePath, basename($sourcePath));
}
$zip->close();
}
catch (\Exception $e) {
throw new RuntimeException("ZIP圧縮処理中にエラーが発生しました: {$e->getMessage()}");
}
}
/**
* ディレクトリ内のファイルを再帰的に取得するプライベートメソッド
*
* @param string $dir 検索対象ディレクトリ
* @return Generator ファイルパスを返すジェネレータ
*/
function getFilesRecursively(string $dir): Generator
{
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($files as $file) {
yield $file->getRealPath();
}
}
// 使用例
$compression = new Utils\CompressionUtils();
try {
$compression->compressToZip('/path/to/source', '/path/to/output.zip');
}
catch (RuntimeException $e) {
echo "エラーが発生しました: " . $e->getMessage();
}