Skip to content

Instantly share code, notes, and snippets.

@kodie
Last active September 16, 2016 14:51
Show Gist options
  • Save kodie/fdbab5c7e6f5313c88943e82ac065a4a to your computer and use it in GitHub Desktop.
Save kodie/fdbab5c7e6f5313c88943e82ac065a4a to your computer and use it in GitHub Desktop.
Pulls .CSV file contents into an associative array.
<?php
function csv_to_array($file, $line_length="0", $delimiter=",", $enclosure="\"", $escape="\\") {
$csv = array();
$keys = array();
$row = 0;
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, $line_length, $delimiter, $enclosure, $escape)) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
if ($row == 0) {
$keys[$c] = $data[$c];
} else {
$csv[$row-1][$keys[$c]] = $data[$c];
}
}
$row++;
}
fclose($handle);
}
return $csv;
}
$array = csv_to_array("file.csv");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment