Last active
February 11, 2016 19:56
-
-
Save charmoney/c56f7434de223ddee7d8 to your computer and use it in GitHub Desktop.
The memory efficient PHP 5.3.1+ library Goodby CSV provides numerically indexed access to the parsed row data. For CSV files starting with header rows, this technique uses the header row as associative array keys for parsed row data.
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 | |
/** | |
* Parse and process a CSV file using the Goodby CSV library, | |
* using a header row as associative array keys for the data | |
* | |
* https://github.com/goodby/csv | |
* @param string $csv_path Path to the CSV file | |
*/ | |
function process_csv($csv_path) { | |
$config = new Goodby\CSV\Import\Standard\LexerConfig(); | |
$lexer = new Goodby\CSV\Import\Standard\Lexer($config); | |
$interpreter = new Goodby\CSV\Import\Standard\Interpreter(); | |
// Start with the header row | |
$is_header = TRUE; | |
// Initialize the headers array for use in the observer | |
$headers = NULL; | |
$interpreter->addObserver(function (array $raw_row) use (&$is_header, &$headers) { | |
if ($is_header) { | |
// Only 1 header row. All others should be processed normally | |
$is_header = FALSE; | |
// Retain the headers array for future rows | |
$headers = $raw_row; | |
} else { | |
// Combine the headers and current row arrays, | |
// using the headers as keys to the current row's data | |
$row = array_combine($headers, $raw_row); | |
// Do stuff with $row | |
} | |
}); | |
$lexer->parse($csv_path, $interpreter); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment