11
11

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 5 years have passed since last update.

変則的なCSVを処理する

Last updated at Posted at 2013-03-09
  • 1~2行目がCSV
  • 3行目以降がただのテキスト

のような不規則なCSVを手っ取り早く処理する方法。

data.csv
foo,bar,baz
foo,bar,baz
comment1
comment2
comment3
php.php
<?php
$csv = new SplFileObject('data.csv');
$line1 = $csv->fgetcsv();
$line2 = $csv->fgetcsv();
$line3 = $csv->fgets();
$line4 = $csv->fgets();
$line5 = $csv->fgets();

var_dump($line1, $line2, $line3, $line4, $line5);

上記のように書くと

  • 1~2行目は配列になる。
  • 3~5行目は文字列になる。
output
array(3) {
  [0] =>
  string(3) "foo"
  [1] =>
  string(3) "bar"
  [2] =>
  string(3) "baz"
}
array(3) {
  [0] =>
  string(3) "foo"
  [1] =>
  string(3) "bar"
  [2] =>
  string(3) "baz"
}
string(9) "comment1\n"
string(9) "comment2\n"
string(9) "comment3\n"
11
11
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?