PHP言語の素で自分もやってみた🙆

20240616

Logging

おはようございます、素のPHP言語でストリーミングダウンロードしてみました.仕事でつい最近、そのような事をLaravelで行ったわけですけど、素のPHPではどんな感じであろうかと思ったのと株式会社Oさんのブログでもストリーミングダウンロードでメモリ不足解消という記事を見つけたので自分の知見で書いてみました.

<?php

class streamDownload
{
    public $flg = false;
    public $fileName = '';
    public $to_encoding = 'sjis';
    public $from_encoding = 'UTF-8';

    public function __construct($fileName,$to_encoding = 'sjis',$from_encoding = 'UTF-8')
    {
        $this->fileName = $fileName;
        return $this;
    }

    public function checkSplFileInfo()
    {
        if((new SplFileInfo($this->fileName))->getExtension() === 'csv'){
            $this->flg = true;
        }
        return $this;
    }

    public function download($data)
    {
        if(!$this->flg){
            return $this->flg;
        }

        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.$this->fileName);        
        $stream = fopen('php://output', 'w');
            foreach ($data as $row) {
                $row = mb_convert_encoding($row,$this->to_encoding,$this->from_encoding);
                fputcsv($stream, $row);
            }
        fclose($stream);
        exit;
    }
}

$data = [
    ['テスト1', '高知太郎', 'abc@example.com'],
    ['テスト2', '高知花子', 'def@example.com'],
    ['テスト3', '高知喜多郎', 'dev@example.com'],
];

(new streamDownload('test.csv'))->checkSplFileInfo()->download($data);

このコードはCSVファイルをエクセルで開くことを想定して記載しています.要のデータ処理はあのような配列で渡せば何万件もの処理でも基本落ちません.

なお要のデータ処理はご自身で考える必要があります、あくまでも雛形です.

明日へ続く.

著者名  @taoka_toshiaki

Profile
高知県在住の@taoka_toshiakiです、記事を読んで頂きありがとうございます.
数十年前から息を吸うように日々記事を書いてます.たまに休んだりする日もありますがほぼ毎日投稿を心掛けています😅.
SNSも使っています、フォロー、いいね、シェア宜しくお願い致します🙇.
SNS::@taoka_toshiaki

タグ

$flg, abc@example.com, application, attachment, construct, Content-Disposition, def@example.com, download, exit, fclose, filename, fopen, foreach, getExtension, header, Laravel, octet-stream, ストリーミングダウンロード,