ILIAS  release_5-1 Revision 5.0.0-5477-g43f3e3fab5f
CSVParser.php
Go to the documentation of this file.
1<?php
2
3namespace SimpleExcel\Parser;
4
6
13class CSVParser extends BaseParser implements IParser
14{
21 protected $delimiter;
22
29 protected $file_extension = 'csv';
30
36 public function loadFile($file_path){
37
38 if (!$this->isFileReady($file_path)) {
39 return;
40 }
41
42 $this->loadString(file_get_contents($file_path));
43 }
44
50 public function loadString($str){
51 $this->table_arr = array();
52
53 if(!isset($this->delimiter)){
54 $numofcols = NULL;
55 // assume the delimiter is semicolon
56 while(($line = str_getcsv($str, ';')) !== FALSE){
57 if($numofcols === NULL){
58 $numofcols = count($line);
59 }
60 // check the number of values in each line
61 if(count($line) === $numofcols){
62 array_push($this->table_arr, $line);
63 } else {
64 // maybe wrong delimiter
65 // empty the array back
66 $this->table_arr = array();
67 $numofcols = NULL;
68 break;
69 }
70 }
71 // if null, check whether values are separated by commas
72 if($numofcols === NULL){
73 while(($line = str_getcsv($str, ',')) !== FALSE){
74 array_push($this->table_arr, $line);
75 }
76 }
77 } else {
78 while(($line = str_getcsv($str, $this->delimiter)) !== FALSE){
79 array_push($this->table_arr, $line);
80 }
81 }
82 }
83
89 public function setDelimiter($delimiter){
90 $this->delimiter = $delimiter;
91 }
92}
isFileReady($file_path)
Check whether file exists, valid, and readable.
Definition: BaseParser.php:169
setDelimiter($delimiter)
Set delimiter that should be used to parse CSV document.
Definition: CSVParser.php:89
loadFile($file_path)
Load the CSV file to be parsed.
Definition: CSVParser.php:36
loadString($str)
Load the string to be parsed.
Definition: CSVParser.php:50
define parser interface
Definition: IParser.php:14