テスト用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 => 'ぴよ',
)
ハマったので備忘。