Skip to content

Instantly share code, notes, and snippets.

@mlconnor
Last active December 13, 2015 17:09
Show Gist options
  • Save mlconnor/4945847 to your computer and use it in GitHub Desktop.
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.
<?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