Created
October 23, 2019 12:56
-
-
Save kobus1998/45f4ce504aba2180f334c768c3f8d4bb to your computer and use it in GitHub Desktop.
simple no abstraction csv parser
This file contains hidden or 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 parseCsv($csv, $delimiter = ',') | |
{ | |
// parse rows | |
$rows = explode("\n", trim($csv)); | |
// parse header and header columns | |
$header = explode($delimiter, trim(reset($rows))); | |
// remove header | |
unset($rows[0]); | |
$result = []; | |
foreach($rows as $lineNr => $line) | |
{ | |
// parse columns | |
$columns = explode($delimiter, trim($line)); | |
foreach($columns as $index => $value) { | |
// add column value together with header column name | |
$result[$lineNr][$header[$index]] = $value; | |
} | |
} | |
return $result; | |
} | |
$csv = 'id,name,email | |
1,jan,[email protected] | |
2,jaap,[email protected] | |
3,cas,[email protected] | |
'; | |
$aCsv = parseCsv($csv); | |
print_r($aCsv); | |
/* | |
Array | |
( | |
[1] => Array | |
( | |
[id] => 1 | |
[name] => jan | |
[email] => [email protected] | |
) | |
[2] => Array | |
( | |
[id] => 2 | |
[name] => jaap | |
[email] => [email protected] | |
) | |
[3] => Array | |
( | |
[id] => 3 | |
[name] => cas | |
[email] => [email protected] | |
) | |
) | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment