Skip to content

Instantly share code, notes, and snippets.

@UziTech UziTech/csv_to_array.php

Last active Jul 8, 2016
Embed
What would you like to do?
Convert a csv file to an array
/**
* Convert a comma separated file into an array.
*
* @param string $filename Path to the CSV file
* @param string[]|bool $header An array used for the keys for an associative array. If set to TRUE then the first row of the file is used as the header. If set to FALSE then a numbered array is used instead.
* @param string $delimiter The separator used in the file
* @return string[][]
* @link http://gist.github.com/385876
* @author Jay Williams <http://myd3.com/>
* @copyright Copyright (c) 2010, Jay Williams
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
function csv_to_array($filename, $header = true, $delimiter = ',') {
$data = [];
if (file_exists($filename) && is_readable($filename)) {
if (($handle = fopen($filename, 'r')) !== false) {
while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) {
if ($header) {
if ($header === true) {
$header = $row;
} else {
$data[] = array_combine($header, $row);
}
} else {
$data[] = $row;
}
}
fclose($handle);
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.