Last active
August 29, 2015 14:04
-
-
Save mamchenkov/b366c5076d63c593475d to your computer and use it in GitHub Desktop.
Quick and easy CSV parser into associative array
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 | |
// 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