Last active
June 4, 2019 22:09
-
-
Save imacrayon/eebc798357ff0204dee053b710a45b4c to your computer and use it in GitHub Desktop.
An "action class" to read CSV data into an associative array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ReadCsv | |
{ | |
private $handler; | |
public function __destruct() | |
{ | |
if ($this->handler) { | |
fclose($this->handler); | |
} | |
} | |
public function __invoke($path, $header = true, $delimiter = ',', $length = 1000) | |
{ | |
$this->handler = fopen($path, 'r'); | |
if ($header) { | |
$header = fgetcsv($this->handler, $length, $delimiter); | |
} | |
$data = []; | |
while (($row = fgetcsv($this->handler, $length, $delimiter, '"', '"')) !== false) { | |
$data[] = $header ? array_combine($header, $row) : $row; | |
} | |
return $data; | |
} | |
} | |
// $data = (new ReadCsv)($path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment