LoginSignup
0
1

More than 3 years have passed since last update.

PHPでShift_JISのcsvファイルをパースするとcsvが壊れる

Posted at

PHPでcsvファイルをパースしようと思ったのですが、文字列にカンマが混入しているところがうまくパースできませんでした。"文字列,文字列"となっている部分のカンマが項目の区切りのカンマと認識されてしまいます。

解決方法

"文字列,文字列"という部分は通常文字列リテラルの"で囲われているので文字列として認識されるはずなのですが、Shift_JISのファイルについてはうまくいきません。

一旦ファイルの中身をUTF-8に変換して、tmpファイルに保存した後に、csvファイルとして読み込むとうまく認識することができます。


$sJisFile = file_get_contents($file->path());
$utf8File = mb_convert_encoding($sJisFile, 'UTF-8', 'SJIS');
$fp = tmpfile();
$meta = stream_get_meta_data($fp);
fwrite($fp, $utf8File);
rewind($fp);

$file = new \SplFileObject($meta['uri']);
$file->setFlags(\SplFileObject::READ_CSV);

foreach($file as $line) {
    var_dump($line);
}

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