PHPの基礎 - 圧縮・解凍

2024年11月9日 (土) 18:10時点におけるWiki (トーク | 投稿記録)による版 (ページの作成:「== 概要 == <br><br> == 圧縮 == ==== ZIP形式 ==== <syntaxhighlight lang="php"> declare(strict_types=1); namespace Utils; use RuntimeException; use ZipArchive; use Generator; /** * ZIP形式で圧縮を行うメソッド * * @param string $sourcePath 圧縮対象のパス(ファイルまたはディレクトリ) * @param string $destinationPath 出力先のZIPファイルパス * @throws RuntimeException 圧縮処理中のエラー発…」)
(差分) ← 古い版 | 最新版 (差分) | 新しい版 → (差分)
📢 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();
 }