Skip to content

Instantly share code, notes, and snippets.

@simonrjones
Last active August 29, 2015 14:10
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 simonrjones/74ca236a2ddc752245e7 to your computer and use it in GitHub Desktop.
Save simonrjones/74ca236a2ddc752245e7 to your computer and use it in GitHub Desktop.
Parse CSV file snippet
<?php
// Read CSV file
// PHP5.4+
ini_set('auto_detect_line_endings', true);
$file = new SplFileObject("path/to/file.csv");
$file->setFlags(SplFileObject::READ_CSV);
$line = 0;
$headers = [];
foreach ($file as $row) {
$line++;
$data = [];
// Build headers
if ($line === 1) {
$headers = $row;
continue;
}
if (empty($headers)) {
throw new Exception("You must define your column headers on row 1");
}
// Assign CSV headers as keys
array_walk($row, function($value, $key) use ($headers, &$data) {
$data[$headers[$key]] = $value;
});
// @todo Process row $data, add your code here
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment