|
1
|
|
|
<?php |
|
2
|
|
|
/* |
|
3
|
|
|
GESTCONV - Aplicación web para la gestión de la convivencia en centros educativos |
|
4
|
|
|
|
|
5
|
|
|
Código adaptado de http://php.net/manual/es/function.fgetcsv.php#68213 |
|
6
|
|
|
*/ |
|
7
|
|
|
|
|
8
|
|
|
namespace AppBundle\Utils; |
|
9
|
|
|
|
|
10
|
|
|
class CsvImporter |
|
11
|
|
|
{ |
|
12
|
|
|
private $fp; |
|
13
|
|
|
private $parse_header; |
|
14
|
|
|
private $header; |
|
15
|
|
|
private $delimiter; |
|
16
|
|
|
private $length; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct($file_name, $parse_header=true, $delimiter=",", $length=0) |
|
19
|
|
|
{ |
|
20
|
|
|
$this->fp = fopen($file_name, "r"); |
|
21
|
|
|
$this->parse_header = $parse_header; |
|
22
|
|
|
$this->delimiter = $delimiter; |
|
23
|
|
|
$this->length = $length; |
|
24
|
|
|
|
|
25
|
|
|
if ($this->parse_header) { |
|
26
|
|
|
$this->header = fgetcsv($this->fp, $this->length, $this->delimiter); |
|
27
|
|
|
foreach($this->header as $key => $data) { |
|
28
|
|
|
$this->header[$key] = iconv('ISO-8859-1', 'UTF-8', $data); |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function __destruct() |
|
35
|
|
|
{ |
|
36
|
|
|
if ($this->fp) { |
|
37
|
|
|
fclose($this->fp); |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
public function get($max_lines=0) |
|
42
|
|
|
{ |
|
43
|
|
|
//if $max_lines is set to 0, then get all the data |
|
44
|
|
|
|
|
45
|
|
|
$data = array(); |
|
46
|
|
|
|
|
47
|
|
|
if ($max_lines > 0) { |
|
48
|
|
|
$line_count = 0; |
|
49
|
|
|
} |
|
50
|
|
|
else { |
|
51
|
|
|
$line_count = -1; // so loop limit is ignored |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE) |
|
55
|
|
|
{ |
|
56
|
|
|
foreach($row as $key => $key_data) { |
|
57
|
|
|
$row[$key] = iconv('ISO-8859-1', 'UTF-8', $key_data); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
if ($this->parse_header) { |
|
61
|
|
|
$row_new = array(); |
|
62
|
|
|
foreach ($this->header as $i => $heading_i) { |
|
63
|
|
|
$row_new[$heading_i] = $row[$i]; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
$data[] = $row_new; |
|
67
|
|
|
} |
|
68
|
|
|
else { |
|
69
|
|
|
$data[] = $row; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
if ($max_lines > 0) { |
|
73
|
|
|
$line_count++; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
return $data; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|