Last active
December 13, 2015 17:09
-
-
Save mlconnor/4945847 to your computer and use it in GitHub Desktop.
This awesome function will return an array of rows with the key values of each row matching the column header which should be provided in the first row.
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 | |
$array = csv_to_array(file_get_contents('some_file.csv')); | |
$json = json_encode($array); | |
echo $json; | |
/** | |
* This awesome function will return an | |
* array of rows with the key values of | |
* each row matching the column header | |
* which should be provided in the first row. | |
*/ | |
function csv_to_array($file_contents) { | |
$objects = array(); | |
$lines = preg_split('|\s*[\r\n]+\s*|msi', $file_contents); | |
$header = array(); | |
foreach ($lines as $index => $line) { | |
$values = str_getcsv($line); | |
if ( $index == 0 ) { | |
$header = $values; | |
} else { | |
$item = array(); | |
foreach ($header as $hIndex => $name) { | |
$item[$name] = $hIndex < count($values) ? $values[$hIndex] : ""; | |
} | |
$objects[] = $item; | |
} | |
} | |
return $objects; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment