Skip to content

Instantly share code, notes, and snippets.

@fjahn
Last active September 1, 2021 14:54
Show Gist options
  • Save fjahn/b88a7abdbc1a9bb24f9599afc5cfdfcc to your computer and use it in GitHub Desktop.
Save fjahn/b88a7abdbc1a9bb24f9599afc5cfdfcc to your computer and use it in GitHub Desktop.
Parse CSV file
<?php
function readCsv(string $filepath, string $separator = ';'): array
{
$csv = file_get_contents($filepath);
$lines = explode("\n", $csv);
$head = str_getcsv(array_shift($lines), $separator);
$data = [];
$lineNumber = 1;
foreach ($lines as $line) {
$lineNumber++;
$line = trim($line);
if ($line === '') continue;
try {
$data[] = array_combine($head, str_getcsv($line, $separator));
} catch (Throwable $throwable) {
throw new Exception("Error occurred when parsing $name at line $lineNumber: '$line'", previous: $throwable);
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment