LoginSignup
3
1

More than 5 years have passed since last update.

FlysystemでCSVを作成・zip化してサーバにアップロードしたメモ

Last updated at Posted at 2018-04-17

背景

取得した配列データをCSV化の上zipファイルにまとめ、
そのzipファイルを外部サーバにアップロードしたいことがありました。
その処理にFlysystemというFilesystemを簡単に扱えるようにしたシステムを使用しました。
手探りで実装したのですが成功した処理をメモとして残します。
※Qiitaアップ用に元の処理を書き換えているためこのままでは正常に動かない可能性があります。

前提

Flysystemをインストールしてあること

ソース

Zip Archive

Zipファイルをローカルに保存する処理

zip_archive.php
use League\Flysystem\Filesystem;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;
use League\Flysystem\Config;

$zip_file = 'file.zip';

// league/flysystem-ziparchive
$filesystem = new Filesystem(new ZipArchiveAdapter($zip_file));

if (!$filesystem){
    return 'LINE:' . __LINE__ . ' new Filesystem がfalse';
}

$str_1 = '"値1","値2","値3"\r\n"値4","値5","値6"\r\n';
$path_1 = '/file_1.csv';
// ZIPにcsvファイルを書き込み
$wrote_1 = $filesystem->write($path_1, $str_1);
if (!$wrote_1){
    return 'LINE:' . __LINE__ . ' $filesystem->write がfalse';
}

// 対象のzipに複数のcsvを続けて書き込むことができる
$str_2 = '"値1","値2","値3"\r\n"値4","値5","値6"\r\n';
$path_2 = '/file_2.csv';
// ZIPにcsvファイルを書き込み
$wrote_2 = $filesystem->write($path_2, $str_2);
if (!$wrote_2){
    return 'LINE:' . __LINE__ . ' $filesystem->write がfalse';
}

// Zipを強制的に保存
$closed = $filesystem->getAdapter()->getArchive()->close();

SFTP

ローカルのZipファイルを外部サーバにアップロードする処理

sftp.php
use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;
use League\Flysystem\Adapter\Local;
use League\Flysystem\Config;

$file_name = 'file.zip';

// アップロード対象のzipのパス
$local_zip_dir = 'local/path/to/zip';
$local = new Filesystem(new Local($local_zip_dir));

// 外部サーバの指定
// league/flysystem-sftp
$sftpConfig = [
    'host' => 'example.com',
    'port' => 22,
    'username' => 'username',
    'password' => 'password',
    'privateKey' => 'path/to/or/contents/of/privatekey',// パスを指定するときは.pem
    'root' => '/path/to/root',
    'timeout' => 10,
    'permPublic' => 0775,
];
$remote = new FileSystem($sftpConfig);

if($local->has($file_name)){
    $contents = $local->read($file_name);
    $wrote = $remote->write($file_name, $contents, ['visibility'=>'public']);

    if (!$wrote){
        return false;
    }
}

外部サーバの保存先ディレクトリの権限によっては保存ができなかったので注意すると良いです。

参考

https://flysystem.thephpleague.com/
http://wern-ancheta.com/blog/2015/09/13/working-with-the-filesystem-with-flysystem/

3
1
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
3
1