LoginSignup
1
1

More than 3 years have passed since last update.

【PHP】gzip圧縮されたCSVをSplFileObjectで直接処理する

Posted at

テスト用gzipファイルの準備

$ cat << EOF > test.csv
> id,name
> 1,ほげ
> 2,ふが
> 3,ぴよ
> EOF
$ gzip -c test.csv > test.csv.gz

実装

<?php
// gzipファイルのダウンロード
$url = 'http://localhost/test.csv.gz';
$ch  = curl_init($url);

$tmp = tmpfile();

curl_setopt_array($ch, [
    CURLOPT_URL  => $url,
    CURLOPT_FILE => $tmp,
]);

curl_exec($ch);
$tmp_path = stream_get_meta_data($tmp)['uri'];

// CSVとして読み込み
$file = new SplFileObject('compress.zlib://' . $tmp_path);
$file ->setFlags(SplFileObject::READ_CSV);

if(0 === strpos(PHP_OS, 'WIN')) {
    setlocale(LC_CTYPE, 'C');
}

foreach($file as $row){
    var_export($row);
}

実行結果

array (
  0 => 'id',
  1 => 'name',
)array (
  0 => '1',
  1 => 'ほげ',
)array (
  0 => '2',
  1 => 'ふが',
)array (
  0 => '3',
  1 => 'ぴよ',
)

ハマったので備忘。

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