@@ -383,19 +383,44 @@ public static function set_values($defaults, $values, $default_key = "") {
383
383
/**
384
384
* Read CSV from URL or File
385
385
* @param string $filename Filename
386
- * @param string $delimiter Delimiter
386
+ * @param string $headers Delimiter
387
387
* @return array [description]
388
388
*/
389
- public static function read_csv ($ filename , $ delimiter = ", " ) {
390
- $ file_data = [];
389
+ public static function read_csv ($ filename , $ with_header = true , $ headers = null , $ delimiter = ', ' ) {
390
+ $ data = array ();
391
+ $ index = 0 ;
392
+ $ header_count = $ headers ? count ($ headers ) : 0 ;
393
+
391
394
$ handle = @fopen ($ filename , "r " ) or false ;
392
395
if ($ handle !== FALSE ) {
393
- while (($ data = fgetcsv ($ handle , 1000 , $ delimiter )) !== FALSE ) {
394
- $ file_data [] = $ data ;
396
+ while (($ row = fgetcsv ($ handle , 0 , $ delimiter )) !== FALSE ) {
397
+ if ($ index == 0 && $ with_header ) {
398
+ if (!$ headers ) $ headers = $ row ;
399
+ $ header_count = count ($ headers );
400
+ } else {
401
+ if ($ headers ) {
402
+ $ column_count = count ($ row );
403
+ if ($ header_count > $ column_count ) {
404
+ $ row = array_merge ($ row , array_fill_keys (range ($ column_count , $ header_count - 1 ), null ));
405
+ } else if ($ header_count < $ column_count ) {
406
+ $ extracted = array_splice ($ row , $ header_count );
407
+ $ row [$ header_count - 1 ] = $ row [$ header_count - 1 ].'| ' .implode ('| ' , $ extracted );
408
+ trigger_error ('read_csv: row ' .$ index .' column mismatch. headers: ' .$ header_count .', columns: ' .$ column_count );
409
+ }
410
+
411
+ $ data [] = array_combine ($ headers , $ row );
412
+ } else {
413
+ $ data [] = $ row ;
414
+ }
415
+ }
416
+
417
+ $ index ++;
395
418
}
419
+
396
420
fclose ($ handle );
397
421
}
398
- return $ file_data ;
422
+
423
+ return $ data ;
399
424
}
400
425
/**
401
426
* Parse email address string
0 commit comments