Skip to content

Instantly share code, notes, and snippets.

@LeoBenoist
Last active June 17, 2021 09:33
Show Gist options
  • Save LeoBenoist/a9e1a042dd72e8bab3a9e2d79ba4cfd0 to your computer and use it in GitHub Desktop.
Save LeoBenoist/a9e1a042dd72e8bab3a9e2d79ba4cfd0 to your computer and use it in GitHub Desktop.
Csv Simple Reader
<?php
function readCsv(string $filename, string $delimiter = ',', string $enclosure = '"', string $escape = '\\'){
ini_set('auto_detect_line_endings', true);
$row = 0;
$headers = [];
if (($handle = fopen($filename, 'r')) !== FALSE) {
while (($data = fgetcsv($handle, 0, $delimiter, $enclosure, $escape)) !== FALSE) {
$row++;
if(1 === $row){
$headers= $data;
continue;
}
$keyValueData = [];
$isLineEmpty = true;
foreach ($headers as $key => $value){
if (in_array($data[$key], ['#REF!', '#N/A'])) {
$data[$key] = null;
}
if (!empty($data[$key])) {
$isLineEmpty = false;
}
$keyValueData[$value] = $data[$key];
}
if($isLineEmpty){
continue;
}
yield ($row-1) => $keyValueData;
}
fclose($handle);
}
ini_set('auto_detect_line_endings', false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment