Advertisement
urosevic

Parse CSV from file to associative array

Oct 27th, 2016
253
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.92 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Read CSV file, parse and return associative array (array_combine).
  5.  * @param  string  $file      Path to CSV file.
  6.  * @param  integer $length    Length of characters to be found in CSV file.
  7.  * @param  string  $delimiter Field delimiter.
  8.  * @param  string  $enclosure Field enclosure character.
  9.  * @return array              Associative array with CSV field head as keys.
  10.  */
  11. function parse_csv( $file = null, $length = 2048, $delimiter = ',', $enclosure = '"' ) {
  12.     if ( ! $file || ! is_file( $file ) ) {
  13.         return null;
  14.     }
  15.     if ( false === ( $handle = fopen( $file, 'r' ) ) ) {
  16.         return null;
  17.     }
  18.     while ( false !== ( $row = fgetcsv( $handle, $length, $delimiter, $enclosure ) ) ) {
  19.         if ( empty( $keys ) ) {
  20.             $keys = $row;
  21.             continue;
  22.         }
  23.         $csv[] = array_combine( $keys, $row );
  24.     }
  25.     fclose( $handle );
  26.     return $csv;
  27. }
  28.  
  29. // Run parser and dump result.
  30. var_dump( parse_csv( 'data/dump.csv' ) );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement