Last active
August 29, 2015 14:10
-
-
Save simonrjones/74ca236a2ddc752245e7 to your computer and use it in GitHub Desktop.
Parse CSV file snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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