Last active
July 22, 2018 17:00
-
-
Save fieldAbyss/0c1974f4b87d78c4c0f218cbf1ba7ab1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* CSVローダー | |
* | |
* @param string $csvfile CSVファイルパス | |
* @param string $mode `sjis` ならShift-JISでカンマ区切り、 `utf16` ならUTF-16LEでタブ区切りのCSVを読む。'utf8'なら文字コード変換しないでカンマ区切り。 | |
* @return array ヘッダ列をキーとした配列を返す | |
*/ | |
function get_csv($csvfile, $mode='sjis') | |
{ | |
// ファイル存在確認 | |
if(!file_exists($csvfile)) return false; | |
// 文字コードを変換しながら読み込めるようにPHPフィルタを定義 | |
if($mode === 'sjis') $filter = 'php://filter/read=convert.iconv.cp932%2Futf-8/resource='.$csvfile; | |
else if($mode === 'utf16') $filter = 'php://filter/read=convert.iconv.utf-16%2Futf-8/resource='.$csvfile; | |
else if($mode === 'utf8') $filter = $csvfile; | |
// SplFileObject()を使用してCSVロード | |
$file = new SplFileObject($filter); | |
if($mode === 'utf16') $file->setCsvControl("\t"); | |
$file->setFlags( | |
SplFileObject::READ_CSV | | |
SplFileObject::SKIP_EMPTY | | |
SplFileObject::READ_AHEAD | |
); | |
// 各行を処理 | |
$records = []; | |
foreach ($file as $i => $row) | |
{ | |
// 1行目はキーヘッダ行として取り込み | |
if($i===0) { | |
foreach($row as $j => $col) $colbook[$j] = $col; | |
continue; | |
} | |
// 2行目以降はデータ行として取り込み | |
$line = []; | |
foreach($colbook as $j=>$col) $line[$colbook[$j]] = @$row[$j]; | |
$records[] = $line; | |
} | |
return $records; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment