Skip to content

Instantly share code, notes, and snippets.

@mamchenkov
Last active August 29, 2015 14:04
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 mamchenkov/b366c5076d63c593475d to your computer and use it in GitHub Desktop.
Save mamchenkov/b366c5076d63c593475d to your computer and use it in GitHub Desktop.
Quick and easy CSV parser into associative array
<?php
// Data CSV file
$fileName = 'data.csv';
// Try to open the CSV file
$fh = fopen($fileName, 'r');
if (!is_resource($fh)) {
die("Failed to open $fileName");
}
$firstLine = true;
$headers = array();
$result = array();
while (($data = fgetcsv($fh)) !== false) {
// If first line, then this are headers
if ($firstLine) {
$headers = $data;
foreach ($headers as $header) {
$result[ $header ] = array();
}
}
// Otherwise, this is data
else {
$line = $data;
foreach ($line as $index => $column) {
$result[ $headers[$index] ][] = $column;
}
}
// Not first line after the first run
$firstLine = false;
}
fclose($fh);
print_r($result);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment