Das Lesen einer csv-Datei in PHP ist eigentlich sehr einfach. Mit folgender Klasse wird der Zugriff auf CSV-Dateien noch komfortabler.
Die Klasse bietet folgende Funktionen:
- Einlesen einer CSV-Datei und Zugriff auf die einzelnen Werte über den Spaltennamen
Hier kann angegeben werden, wieviel Kopfzeilen die Datei hat und ab welcher Zeile die Daten beginnen. Um auf die einzelnen Werte mittels Name zugreifen zu können, muß die erste Zeile in der CSV-Datei die Spaltennamen beinhalten. Ansonsten kann nur mit den Indexen zugegriffen werden. - Erstellen eines CSV-Downloads
Beispiel: Einlesen einer CSV-Datei
1 2 3 4 5 6 7 8 9 10 11 12 13 |
$csv = new Csv(); $csv->read('test.csv'); while (!$csv->eof()) { echo $csv->getVal('Spaltenname1') . ' ' . $csv->getVal('Spaltenname2'); // oder mit Spalten-Index echo $csv->getVal(1) . ' ' . $csv->getVal(2); // oder direkt über Spaltenname echo $csv->Spaltenname1 . ' ' . $csv->Spaltenname2; // nächste Zeile $csv->next(); } |
Beispiel: Erstellen eines CSV-Downloads
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$csv = new Csv(); $csv->setColumnNames(array('Spalte1', 'Spalte2')); // hinzufügen einer Spalte $csv->addColumnName('Spalte3'); // mit Beispiel-Inhalt befüllen for ($row = 1; $row < 5; $row++) { for ($col = 1; $row <= 3; $col++) { $csv->addRowArray(array('Wert1', 'Wert2', 'Wert3')); } } $csv->download('test.csv'); |
CSV-Klasse:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 |
<?php class Csv { /** * Column names found or created * @var array */ private $columnNames = array(); /** * Number of rows found or created * @var integer */ private $rowNum = 0; /** * Actual row number * @var integer */ private $aktRow = 1; /** * Whether the values should be automatically utf-8 encoded when read * @var boolean */ private $doUtfEncode = true; /** * Whether the values should be automatically utf-8 decoded when set * @var boolean */ private $doUtfDecode = true; /** * Internal data representation * @var array */ private $data; /** * Whether quotes in values added should change the single " to double "" * @var boolean */ private $autoQuote = true; public function __construct() { } /** * Analyse csv file and save it in array * * @param string $filename filename/path to csv file * @param integer $headersRow number of header rows * @param integer $dataStartRow line-number where the data to read starts */ public function read($filename, $headersRow = 1, $dataStartRow = 2) { $fp = fopen($filename, 'r'); $row = 1; $dataRow = 0; // Initialize $this->columnNames = array(); $this->rowNum = 0; $this->data = array(); $this->aktRow = 1; while (($vals = fgetcsv($fp, 0, ';')) !== FALSE) { $col = 1; if ($row >= $dataStartRow) { $this->rowNum ++; $dataRow ++; } foreach ($vals as $val) { if ($row == $headersRow) { $this->columnNames[$col] = strtolower(trim($val)); } if ($row >= $dataStartRow) { $this->data[$dataRow][$col] = $val; } $col++; } $row ++; } fclose($fp); } /** * Get a val of the Array, either with column name or column index and the row (optinoal) * * @param int $columnNameOrCol Can be the column name or a integer which indicates its a column index * @param int $row Optional: the row index (uses the actual row if not given) * @return string */ public function getVal($columnNameOrCol, $row = -1) { if ($row == -1) { $row = $this->aktRow; } if (is_int($columnNameOrCol)) { $col = $columnNameOrCol; } else { if (($col = array_search(strtolower(trim($columnNameOrCol)), $this->columnNames)) === FALSE) { return FALSE; } } if (isset($this->data[$row][$col])) { $val = $this->data[$row][$col]; if ($this->doUtfEncode) { $val = utf8_encode($val); } return $val; } else { return FALSE; } } /** * Short for getVal() * * @param int $columnNameOrCol * @param int $row * @return string */ public function val($columnNameOrCol, $row = -1) { return $this->getVal($columnNameOrCol, $row); } /** * Magic method to get a value by its column name * * @param string $name column name * @return string */ public function __get($name) { return $this->getVal($name); } /** * Checks if end of file is reached * * @return boolean */ public function eof() { if ($this->aktRow > $this->rowNum) { return true; } else { return false; } } /** * Go to next row */ public function next() { $this->aktRow ++; } public function nextRow() { $this->next(); } /** * Get number of rows * * @return integer */ public function getRowNum() { return $this->rowNum; } /** * Get the column names * * @return array */ public function getColumnNames() { return $this->columnNames; } /** * Add data array to the actual row * * @param array $rowArray */ public function addRowArray($rowArray) { $this->data[$this->aktRow] = []; foreach ($rowArray as $val) { $this->addVal(); } $this->aktRow++; } /** * Add a value to the actual row * * @param type $val */ public function addVal($val) { if ($this->doUtfDecode) { $val = utf8_decode($val); } if ($this->autoQuote) { $val = str_replace('"', '""', $val); } $this->data[$this->aktRow][] = '"' . $val . '"'; } /** * Set column names from array * * @param array $columnNames */ public function setColumnNames($columnNames) { $this->columnNames = $columnNames; } /** * Add a column name * * @param string $columnName */ public function addColumnName($columnName) { $this->columnNames[] = $columnName; } /** * Start download of the data as csv file * * @param type $filename * @param type $addDateToFilename */ public function download($filename, $addDateToFilename = true) { $f = fopen('php://memory', 'w'); if (sizeof($this->columnNames) > 0) { fwrite($f, implode(';', $this->columnNames)); fwrite($f, "\n"); } foreach ($this->data as $line) { // generate csv lines from the inner arrays fwrite($f, implode(';', $line)); fwrite($f, "\n"); } fseek($f, 0); header('Content-Type: application/csv'); $filename = str_ireplace('.csv', '', $filename); if ($addDateToFilename) { $date = new \DateTime(); $filename .= '_' . $date->format('Y_m_d__H_i'); } $filename .= '.csv'; header('Content-Disposition: attachment; filename="' . $filename . '.csv";'); fpassthru($f); die(); } /** * Dump the data for debugging */ public function dump() { echo '<pre>'; print_r($this->data); echo '</pre>'; } // -------- Getters and setters --------- public function getAutoQuote() { return $this->autoQuote; } public function setAutoQuote($autoQuote) { $this->autoQuote = $autoQuote; } public function getDoUtfDecode() { return $this->doUtfDecode; } public function setDoUtfDecode($doUtfDecode) { $this->doUtfDecode = $doUtfDecode; } public function getUtfEncode() { return $this->doUtfEncode; } public function setUtfEncode($doUtfEncode) { $this->doUtfEncode = $doUtfEncode; } } |