LoginSignup
2
5

More than 5 years have passed since last update.

PHPでcsvファイルを読み込んで、前処理してから、別のcsvファイルにコピーする

Posted at

PHP5.1以降使えるというSplFileObjectを使うと簡単。

// 読み込むcsvファイル
$filepath = './query_result.csv';
$file = new SplFileObject($filepath);
$file->setFlags(SplFileObject::READ_CSV);

// 書き込むcsvファイル
$filepathForCopy = './query_result_copy.csv';
$fileForCopy = new SplFileObject($filepathForCopy, 'w');

// 読み込んで、前処理して、書き込む
foreach ($file as $line) {
    // 空行で無い場合のみ書き込む
    if(!is_null($line[0])) {
        // 必要な前処理を行う
        preprocessing($line[0]);
        // copy用csvファイルに書き込み
        $fileForCopy->fputcsv($line);
    }
}

function preprocessing($value) {
   // csvから読み込んだデータに行う前処理
}

(参考)
https://qiita.com/kazu56/items/06660b0dc8638a6c948f
https://centosinstall.com/programming/php/csv-splfileobject#CSV-3
http://php.net/manual/ja/splfileobject.fputcsv.php

2
5
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
2
5