Skip to content

Instantly share code, notes, and snippets.

@benbalter
Created July 24, 2012 22:28
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save benbalter/3173096 to your computer and use it in GitHub Desktop.
Save benbalter/3173096 to your computer and use it in GitHub Desktop.
Parse CSV into Associative Array
<?php
$lines = explode( "\n", file_get_contents( 'input.csv' ) );
$headers = str_getcsv( array_shift( $lines ) );
$data = array();
foreach ( $lines as $line ) {
$row = array();
foreach ( str_getcsv( $line ) as $key => $field )
$row[ $headers[ $key ] ] = $field;
$row = array_filter( $row );
$data[] = $row;
}
@hboneill
Copy link

This is very helpful. Thank you!

@gkalmoukis
Copy link

This is very helpful!

@wickywills
Copy link

Beautiful

@ypsilon-p
Copy link

It is not a good method to load the whole file into memory. If you have a large file, your application will slow down or you will need a lot of RAM. The better way is to read and process the file line by line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment