ILIAS  trunk Revision v11.0_alpha-3011-gc6b235a2e85
CSVReader.php
Go to the documentation of this file.
1<?php
2
19namespace ILIAS\Survey;
20
21use ilUtil;
22use RuntimeException;
23
28{
33 private string $line_ends;
34 private array $data = [];
35 private string $separator = ';';
36 private string $delimiter = '""';
37 private string $escape = '\\';
38 private int $length = 1024;
39
40 private function parse(): void
41 {
42 $row = 0;
43
44 while (($line = fgetcsv($this->file_resource, $this->length, $this->separator, $this->escape)) !== false) {
45 $line_count = count($line);
46 for ($col = 0; $col < $line_count; $col++) {
47 $this->data[$row][$col] = $this->unquote($line[$col]);
48 }
49
50 ++$row;
51 }
52 }
53
54 public function setSeparator(string $a_sep): void
55 {
56 $this->separator = $a_sep;
57 }
58
59 public function setDelimiter(string $a_del): void
60 {
61 $this->delimiter = $a_del;
62 }
63
64 public function setLength(int $a_length): void
65 {
66 $this->length = $a_length;
67 }
68
69 public function open(string $path_to_file): bool
70 {
71 $this->file_resource = fopen(ilUtil::stripSlashes($path_to_file), "r");
72
73 if (!is_resource($this->file_resource)) {
74 throw new RuntimeException('sould not open stream to ' . $path_to_file);
75 }
76 return true;
77 }
78
79 public function close(): bool
80 {
81 return fclose($this->file_resource);
82 }
83
84 public function getCsvAsArray(): array
85 {
86 $this->parse();
87
88 return $this->data;
89 }
90
91 private function unquote(string $a_str): string
92 {
93 return str_replace($this->delimiter . $this->delimiter, $this->delimiter, $a_str);
94 }
95}
setSeparator(string $a_sep)
Definition: CSVReader.php:54
unquote(string $a_str)
Definition: CSVReader.php:91
setDelimiter(string $a_del)
Definition: CSVReader.php:59
setLength(int $a_length)
Definition: CSVReader.php:64
open(string $path_to_file)
Definition: CSVReader.php:69
Util class various functions, usage as namespace.
static stripSlashes(string $a_str, bool $a_strip_html=true, string $a_allow="")
This file is part of ILIAS, a powerful learning management system published by ILIAS open source e-Le...