urosevic icon

Parse CSV from file to associative array

urosevic | PRO | 10/27/16 09:01:05 PM UTC | 0 ⭐ | 517 👁️ | Never ⏰ | []
PHP |

920 B

|

None

|

0 👍

/

0 👎

<?php
 
/**
 * Read CSV file, parse and return associative array (array_combine).
 * @param  string  $file      Path to CSV file.
 * @param  integer $length    Length of characters to be found in CSV file.
 * @param  string  $delimiter Field delimiter.
 * @param  string  $enclosure Field enclosure character.
 * @return array              Associative array with CSV field head as keys.
 */
function parse_csv( $file = null, $length = 2048, $delimiter = ',', $enclosure = '"' ) {
    if ( ! $file || ! is_file( $file ) ) {
        return null;
    }
    if ( false === ( $handle = fopen( $file, 'r' ) ) ) {
        return null;
    }
    while ( false !== ( $row = fgetcsv( $handle, $length, $delimiter, $enclosure ) ) ) {
        if ( empty( $keys ) ) {
            $keys = $row;
            continue;
        }
        $csv[] = array_combine( $keys, $row );
    }
    fclose( $handle );
    return $csv;
}
 
// Run parser and dump result.
var_dump( parse_csv( 'data/dump.csv' ) );

Comments