Parsing csv/tsv with Laravel 4

We needed to parse tsv files in one of our projects, and I found some nice code to achieve that – https://github.com/goodby/csv

Getting this to work with Laravel is actually quite easy, although undocumented.

1. Add goodby/csv to your composer file

{
    "require": {
        "goodby/csv": "*"
    }
}

2. Update composer

composer update

3. Add the following lines to the aliases array in the app/config/app.php file

'Lexer' => 'GoodbyCSVImportStandardLexer',
'Interpreter' => 'GoodbyCSVImportStandardInterpreter',
'LexerConfig' => 'GoodbyCSVImportStandardLexerConfig',

4. Run your code

$lexer = new Lexer(new LexerConfig());
$interpreter = new Interpreter();
$interpreter->addObserver(function(array $row) {
    // do something here.
    // for example, insert $row to database.
});
$lexer->parse('data.csv', $interpreter);

Full docs can be found at https://github.com/goodby/csv

Leave a Reply

Your email address will not be published. Required fields are marked *