1: <?php
2:
3: namespace SimpleExcel\Parser;
4:
5: use SimpleExcel\Enums\Datatype;
6: use SimpleExcel\Enums\SimpleExcelException;
7: use SimpleExcel\Spreadsheet\Workbook;
8: use SimpleExcel\Spreadsheet\Worksheet;
9: use SimpleExcel\Spreadsheet\Cell;
10:
11: 12: 13: 14: 15: 16:
17: class CSVParser extends BaseParser
18: {
19: 20: 21: 22: 23: 24:
25: protected $delimiter;
26:
27: 28: 29: 30: 31: 32:
33: protected $file_extension = 'csv';
34:
35: 36: 37: 38: 39: 40: 41: 42: 43:
44: public function loadFile ($file_path, $options = NULL) {
45: if ($this->checkFile($file_path)) {
46: $this->loadString(file_get_contents($file_path), $options);
47: }
48: }
49:
50: 51: 52: 53: 54: 55:
56: public function loadString ($str, $options = NULL) {
57: $this->workbook = new Workbook();
58:
59: if (isset($options['delimiter'])) {
60: $this->delimiter = $options['delimiter'];
61: }
62:
63:
64: $pattern = "/\r\n|\n|\r/";
65: $lines = preg_split($pattern, $str, -1, PREG_SPLIT_NO_EMPTY);
66: $total = count($lines);
67:
68:
69: if ($total == 0) {
70: return;
71: }
72:
73:
74: $line = $lines[0];
75: if (!isset($this->delimiter)) {
76:
77: $separators = array(';' => 0, ',' => 0);
78: foreach ($separators as $sep => $count) {
79: $args = str_getcsv($sep, $line);
80: $count = count($args);
81:
82: $separators[$sep] = $count;
83: }
84:
85: $sep = ',';
86: if (($separators[';'] > $separators[','])) {
87: $sep = ';';
88: }
89:
90: $this->delimiter = $sep;
91: }
92:
93:
94: $max = 0;
95: $min = PHP_INT_MAX;
96: $cols = 0;
97: $sep = $this->delimiter;
98: $rows = array();
99: foreach ($lines as $line) {
100: $args = str_getcsv($line, $sep);
101: $rows[] = $args;
102:
103: $cols = count($args);
104: if ($cols > $max) {
105: $max = $cols;
106: }
107: if ($cols < $min) {
108: $min = $cols;
109: }
110: }
111:
112:
113: if ($min != $max) {
114: foreach ($rows as $i => $row) {
115: $c = count($row);
116: while ($c < $max) {
117: $row[] = "";
118: $c += 1;
119: }
120: $rows[$i] = $row;
121: }
122: }
123:
124:
125: foreach ($rows as $i => $row) {
126: foreach ($row as $j => $cell) {
127: $rows[$i][$j] = new Cell($cell, Datatype::TEXT);
128: }
129: }
130: $worksheet = new Worksheet();
131: $worksheet->setRecords($rows);
132: $this->workbook->insertWorksheet($worksheet);
133: }
134: }
135: