0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FuelPHPでZipファイル作成

Posted at
  • いい加減アクセスのたびにMySQL読みに行くのが重い
  • cronで最新データを取得、ファイルを作成してキャッシュの代わりにする
  • cron用のサーバーからアプリケーションサーバーへzipファイルを送信する
    • ユーザー閲覧時にはappサーバーでローカルファイルの読み出しだけを行う

みたいな話。
FuelPHPタグ付けておきながら中身は普通のPHPです。ご容赦ください(´@ω@`)

前提

FuelPHPにはZip作成が無いみたいなのでPHPからZipを作成できるようにしておく必要があります。
コンソールで php -m を叩いてzipが入っていればよし、無ければzip.soを読み込んでやります。
当方の環境(さくらVPS、CentOS6.6)では/usr/lib64/php/modules/にありました。参考までに。

ファイル作成

MySQLにアクセスしてデータを取得、JSONファイルを作成します。

$folowerList=Model_Folower::getAll();
        foreach($folowerList as $folower){
            $id = $folower['screen_name'];
            $new =       Model_Folower::getNewTweetList($id);
            $contents = array("new"=>$new);
            File::create(APPPATH."tmp/data/",$id.".json",json_encode($contents));
        }
        
        $zipPath=Model_Zip::createFeedZip();
        if($zipPath==false){
            $this->response(array('status'=>500));
        }...

ちょっとこの後の処理をどうしようかは悩んでるので取り敢えずここまで。
ファイル作成とZip作成処理の呼び出しが見えればいいかなっと

Zip作成

Model_Zip.php
    public static function createFeedZip()
    {
        $zip = new ZipArchive();
        $zipFileName = date("YmdHi") . '.zip';
        $zipFilePath = APPPATH . "tmp/zip/";
        
        $result = $zip->open($zipFilePath . $zipFileName, ZipArchive::CREATE);
        if ($result != true) {
            return false;
        }
        $filePath = APPPATH . "tmp/data";
        $folder = scandir($filePath);
        
        foreach ($folder as $file) {
            if (is_dir($file))
                continue;
            $zip->addFile($filePath . DS . $file, $file);
        }
        
        if ($zip->close()) {
            // 成功
            return true;
        } else {
            // 失敗
			 return false;
        }
    }

scandirでさっき作成したjsonファイルの一覧を取得し、forループでZipに登録していきます。
scandirは.やら..も一緒に取得してしまい、これを含むとうまくZip作成ができないためis_dirで取り除いています。

add_fileの第二引数は上書きするファイル名。
第一引数でZipに追加するファイルをパスで指定しているんですが、第二引数なしだとフォルダ構成ごと圧縮されてしまったので注意。
ちなみに圧縮されたのはフォルダ構成だけで、フォルダごと圧縮できるわけではありません。
フォルダごと圧縮するにはLINUXコマンド使うしか無いんですかね。今回使わないんでいいですけど別に。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?