Skip to content

Instantly share code, notes, and snippets.

@olimortimer
Last active December 16, 2015 18:50
Show Gist options
  • Save olimortimer/5481143 to your computer and use it in GitHub Desktop.
Save olimortimer/5481143 to your computer and use it in GitHub Desktop.
PHP: Parse CSV into an array
<?php
function parse_csv($filepath, $namedfields = true) {
$max_row_size = 0; // Maximum row size - 0 is unlimited
$delimiter = ','; // The field delimiter
$enclosure = '"'; // The field enclosure character
$fields = $content = false;
// Open our files
$file = fopen($filepath, 'r');
// Get our field names
if($namedfields) $fields = fgetcsv($file, $max_row_size, $delimiter, $enclosure);
// Loop through each row, and add them to our array
while(($row = fgetcsv($file, $max_row_size, $delimiter, $enclosure)) != false) {
if($row[0] != null) {
if(!$content) $content = array();
if($namedfields) {
$items = array();
foreach($fields as $id => $field) {
if(isset($row[$id])) $items[$field] = $row[$id];
}
$content[] = $items;
} else {
$content[] = $row;
}
}
}
// Close our file
fclose($file);
return $content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment