Skip to content

Instantly share code, notes, and snippets.

@imacrayon
Last active June 4, 2019 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imacrayon/eebc798357ff0204dee053b710a45b4c to your computer and use it in GitHub Desktop.
Save imacrayon/eebc798357ff0204dee053b710a45b4c to your computer and use it in GitHub Desktop.
An "action class" to read CSV data into an associative array
<?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