Skip to content

Instantly share code, notes, and snippets.

@mgng
Last active October 4, 2020 04:18
Show Gist options
  • Save mgng/76061cdafa818d51a93b to your computer and use it in GitHub Desktop.
Save mgng/76061cdafa818d51a93b to your computer and use it in GitHub Desktop.
csv file parser for windows/unix
<?php
/**
* @param string $file Shift_JIS の csv ファイルパス
* @return array
*/
function parseCsv($file)
{
$str = file_get_contents($file);
$is_win = strpos(PHP_OS, "WIN") === 0;
// Windowsの場合は Shift_JIS、Unix系は UTF-8で処理
if ( $is_win ) {
setlocale(LC_ALL, "Japanese_Japan.932");
} else {
setlocale(LC_ALL, "ja_JP.UTF-8");
$str = mb_convert_encoding($str, "UTF-8", "SJIS-win");
}
$result = array();
$fp = fopen("php://temp", "r+");
fwrite($fp, str_replace(array("\r\n", "\r" ), "\n", $str));
rewind($fp);
while($row = fgetcsv($fp)) {
// windows の場合はSJIS-win → UTF-8 変換
$result[] = $is_win
? array_map(function($val){return mb_convert_encoding($val, "UTF-8", "SJIS-win");}, $row)
: $row;
}
fclose($fp);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment