ILIAS  release_8 Revision v8.24
class.ilCSVReader.php
Go to the documentation of this file.
1<?php
2
3/******************************************************************************
4 *
5 * This file is part of ILIAS, a powerful learning management system.
6 *
7 * ILIAS is licensed with the GPL-3.0, you should have received a copy
8 * of said license along with the source code.
9 *
10 * If this is not the case or you just want to try ILIAS, you'll find
11 * us at:
12 * https://www.ilias.de
13 * https://github.com/ILIAS-eLearning
14 *
15 *****************************************************************************/
16
22{
23 public const AUTO_DETECT_LINE_ENDINGS = "auto_detect_line_endings";
28 private string $line_ends;
29 private array $data = [];
30 private string $separator = ';';
31 private string $delimiter = '""';
32 private int $length = 1024;
33
34 private function parse(): void
35 {
36 $row = 0;
37
38 while (($line = fgetcsv($this->file_resource, $this->length, $this->separator)) !== false) {
39 $line_count = count($line);
40 for ($col = 0; $col < $line_count; $col++) {
41 $this->data[$row][$col] = $this->unquote($line[$col]);
42 }
43
44 ++$row;
45 }
46 }
47
48 public function setSeparator(string $a_sep): void
49 {
50 $this->separator = $a_sep;
51 }
52
53 public function setDelimiter(string $a_del): void
54 {
55 $this->delimiter = $a_del;
56 }
57
58 public function setLength(int $a_length): void
59 {
60 $this->length = $a_length;
61 }
62
63 public function open(string $path_to_file): bool
64 {
65 $this->line_ends = ini_get(self::AUTO_DETECT_LINE_ENDINGS);
66 ini_set(self::AUTO_DETECT_LINE_ENDINGS, true);
67
68 $this->file_resource = fopen(ilUtil::stripSlashes($path_to_file), "r");
69
70 if (!is_resource($this->file_resource)) {
71 throw new RuntimeException('sould not open stream to ' . $path_to_file);
72 }
73 return true;
74 }
75
76 public function close(): bool
77 {
78 ini_set(self::AUTO_DETECT_LINE_ENDINGS, $this->line_ends);
79
80 return fclose($this->file_resource);
81 }
82
83 public function getCsvAsArray(): array
84 {
85 $this->parse();
86
87 return $this->data;
88 }
89
90 private function unquote(string $a_str): string
91 {
92 return str_replace($this->delimiter . $this->delimiter, $this->delimiter, $a_str);
93 }
94}
setSeparator(string $a_sep)
unquote(string $a_str)
setLength(int $a_length)
const AUTO_DETECT_LINE_ENDINGS
setDelimiter(string $a_del)
open(string $path_to_file)
static stripSlashes(string $a_str, bool $a_strip_html=true, string $a_allow="")