【CodeIgniter】CSVファイルパーサーライブラリ
CodeIgniter3を使っている方はLeague/CSVを利用することをおすすめします。
以下、本文です。
CodeIgniter用のCSVファイルパーサーライブラリを作りました。
CSVファイルパーサーライブラリ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class CsvParser { private $handle; private $file; private $parse_header; private $length; private $delimiter; private $enclosure; public $header; public function __construct() { setlocale(LC_ALL, 'ja_JP.UTF-8'); } public function __destruct() { if(is_resource($this->handle)) { fclose($this->handle); } } public function load($file, $parse_header = FALSE, $length = 50000, $delimiter = ',', $enclosure = '"') { $this->file = $file; $this->parse_header = $parse_header; $this->length = $length; $this->delimiter = $delimiter; $this->enclosure = $enclosure; if(!file_exists($this->file)){ throw new Exception(sprintf("%sが存在しません。", basename($this->file))); } if(($file = file_get_contents($this->file)) === FALSE){ throw new Exception(sprintf("%sを読み込めません。", basename($this->file))); }else{ //テンポラリファイルを作成 $this->handle = tmpfile(); // 文字コード変換 $file = mb_convert_encoding($file, mb_internal_encoding(), mb_detect_encoding($file, 'UTF-8, EUC-JP, JIS, eucjp-win, sjis-win')); // バイナリセーフなファイル書き込み処理 fwrite($this->handle, $file); // ファイルポインタの位置を先頭へ rewind($this->handle); } if ($this->parse_header) { $this->header = fgetcsv($this->handle, $this->length, $this->delimiter, $this->enclosure); $this->header = array_map(function($header){ return preg_replace('/\n|\r/', '', $header); }, $this->header); } } public function parse() { if(!$this->handle){ throw new Exception(sprintf("%s", "ファイルが読み込まれていません。")); } $data = array(); while( ($row = fgetcsv($this->handle, $this->length, $this->delimiter, $this->enclosure)) !== FALSE ) { if($this->header) { foreach($this->header as $i => $heading_i) { if(isset($row[$i])){ $line[$heading_i] = $row[$i]; }else{ throw new Exception(sprintf('%s', "ファイルが不正です。")); } } $data[] = $line; } else { $data[] = $row; } } fclose($this->handle); return $data; } } |
ファイル名をcsvparser.phpとして、application/libraries内に設置して下さい。
CSVファイルパーサーライブラリの使い方
コントローラーのメソッド内に以下のようにライブラリを読み込みます。
1 | $this->load->library('csvparser'); |
次にCSVファイルを読み込みます。
1 | $this->csvparser->load('file.csv'); |
最後にCSVファイルをパースします。
1 | $csv_data = $this->csvparser->parse(); |
以上です。
一行目が項目名の場合は以下のようにCSVファイルを読み込んで下さい。
1 | $this->csvparser->load('file.csv', TRUE); |
コメントを投稿するにはログインが必要です。