Last active
June 17, 2021 09:33
-
-
Save LeoBenoist/a9e1a042dd72e8bab3a9e2d79ba4cfd0 to your computer and use it in GitHub Desktop.
Csv Simple Reader
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 $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