ILIAS  release_5-0 Revision 5.0.0-1144-gc4397b1f87
CSVParser.php
Go to the documentation of this file.
1 <?php
2 
3 namespace SimpleExcel\Parser;
4 
6 
13 class 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 }
setDelimiter($delimiter)
Set delimiter that should be used to parse CSV document.
Definition: CSVParser.php:89
loadString($str)
Load the string to be parsed.
Definition: CSVParser.php:50
define parser interface
Definition: IParser.php:13
isFileReady($file_path)
Check whether file exists, valid, and readable.
Definition: BaseParser.php:169
loadFile($file_path)
Load the CSV file to be parsed.
Definition: CSVParser.php:36