Skip to content

Instantly share code, notes, and snippets.

@WangMagic
Forked from benbalter/parse-csv.php
Last active February 22, 2019 13:56
Show Gist options
  • Save WangMagic/0aa859d4a32dfb92e4d287d365f4f28f to your computer and use it in GitHub Desktop.
Save WangMagic/0aa859d4a32dfb92e4d287d365f4f28f 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 ) {
//Skip if it's just a blank line
if(empty($line)){
continue;
}
$row = array();
foreach ( str_getcsv( $line ) as $key => $field )
$row[ $headers[ $key ] ] = $field;
$row = array_filter( $row );
$data[] = $row;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment