Skip to content

Instantly share code, notes, and snippets.

@foxwoods
Created February 16, 2012 04:51
Show Gist options
  • Save foxwoods/1842139 to your computer and use it in GitHub Desktop.
Save foxwoods/1842139 to your computer and use it in GitHub Desktop.
A PHP function to parse CSV file into big array. The 3rd parameter accepts an array of column names.
<?php
/**
* parse_csv
* parse CSV file into big array
*
* @param string $file
* @param string $separator
* @param array $meta
* @return array
*/
function parse_csv($file, $separator=',', $meta=array()) {
$count = 0;
$data = array();
if (($fp = fopen($file, 'r')) !== false ) {
while (($row = fgetcsv($fp, 1024, $separator)) !== false) {
if ($count === 0 && empty($meta) && strpos($row, '#') !== false) {
$meta = $row;
$meta = array_map(create_function('$s', 'return str_replace("#", "", $s);'), $meta);
}
$data[] = empty($meta) ? $row : array_combine($meta, $row);
$count++;
}
fclose($fp);
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment