CakePHPでCSVをアップロードしてDB更新
エラーチェックはしてません。
Controller
public function upload(){
//フォームでテーブル名を送りつける。
$tableName = $this->request->data['selectTable'];//対象テーブル読み込み
$this->loadModel($tableName);
//該当テーブルのカラム名と属性を取得
$tableType = $this->$tableName->getColumnTypes();
//エンコード※1
$fileName = self::fileEncode();
$fp = fopen($fileName, 'rb');
//saveAllする配列
$updateItemData = array();
//データ取得
while ($row = fgetcsv($fp)) {
//カラムが異なっていたらエラー
if(count($tableType) == count($row)){//1レコード分の配列
$record = array();
//添字
$i = 0;//一括保存用に整形
foreach($tableType as $key => $value){
//例:$record['name'] = 'username'
$record[$key] = $row[$i++];
}
$updateItemData[$tableName][] = $record;
} else {
//カラム数が異なるのでエラー
throw new RuntimeException('Invalid column detected');
}//一括保存
$this->$tableName->saveAll($updateItemData[$tableName]);
}
※1 エンコード
public function fileEncode(){
$detectOrder = 'ASCII,JIS,UTF-8,CP51932,SJIS-win';
setlocale(LC_ALL, 'ja_JP.UTF-8');//ファイルのパスを取得
$tmpName = $this->request->param('form')['upfile']['tmp_name'];
$buffer = file_get_contents($tmpName);
if (!$encoding = mb_detect_encoding($buffer, $detectOrder, true)) {
// 文字コードの自動判定に失敗
unset($buffer);
throw new RuntimeException('Character set detection failed');
}
file_put_contents($tmpName, mb_convert_encoding($buffer, 'UTF-8', $encoding));
unset($buffer);
return $tmpName;
}
出典元は忘れてしまいました…