Last active
September 1, 2021 14:54
-
-
Save fjahn/b88a7abdbc1a9bb24f9599afc5cfdfcc to your computer and use it in GitHub Desktop.
Parse CSV file
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 | |
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