Skip to content

Instantly share code, notes, and snippets.

@UziTech
Last active July 8, 2016 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save UziTech/c264e201e9938c43c0a0da81b94bdbc9 to your computer and use it in GitHub Desktop.
Save UziTech/c264e201e9938c43c0a0da81b94bdbc9 to your computer and use it in GitHub Desktop.
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