3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

セル内に改行があるCSVをPHPで処理する方法

Posted at

fopen でファイルを読み込んで、CSV処理を書いていると、
CSVのセル内に改行があり、ハマったのでメモ

fopen で書いていたがセル内の改行がうまく取得できない

$file = "test.csv";
$fp = fopen($file, "r");
while($line = fgets($fp)) {
    $data = explode(",", $line);

    //DB保存など

}
fclose($fp);

このような感じでコードを書いていたが、
CSVのセル内に改行があると、うまくデータが取得できない

解決方法

SplFileObject クラスを書けば、うまいこと取得してくれた

$file = new SplFileObject($file);
$file->setFlags(
    \SplFileObject::READ_CSV |           
    \SplFileObject::READ_AHEAD |       
    \SplFileObject::SKIP_EMPTY |       
    \SplFileObject::DROP_NEW_LINE 
);


foreach ($file as $data) {
    error_log(print_r($data, true));
    //1行ずつ配列として取得できる
}

超ラク

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?