Last active
December 16, 2015 18:50
-
-
Save olimortimer/5481143 to your computer and use it in GitHub Desktop.
PHP: Parse CSV into an array
This file contains 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 | |
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