| 1 |
<?php |
| 2 |
/** |
| 3 |
* Read CSV file |
| 4 |
* |
| 5 |
* @package Timetics |
| 6 |
*/ |
| 7 |
namespace Timetics\Base; |
| 8 |
|
| 9 |
/** |
| 10 |
* CSV Reader Class |
| 11 |
*/ |
| 12 |
class CsvReader implements FileReaderInterface { |
| 13 |
/** |
| 14 |
* Store file |
| 15 |
* |
| 16 |
* @var string |
| 17 |
*/ |
| 18 |
private static $file; |
| 19 |
|
| 20 |
/** |
| 21 |
* Get data that will be read from csv file |
| 22 |
* |
| 23 |
* @param file $file |
| 24 |
* |
| 25 |
* @return array |
| 26 |
*/ |
| 27 |
public static function get_data( $file ) { |
| 28 |
self::$file = $file; |
| 29 |
|
| 30 |
return self::read_file(); |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Get from file |
| 35 |
* |
| 36 |
* @return array |
| 37 |
*/ |
| 38 |
private static function read_file() { |
| 39 |
$file = self::$file; |
| 40 |
$csv_data = []; |
| 41 |
|
| 42 |
$handle = fopen( $file, 'r' ); |
| 43 |
$headers = fgetcsv( $handle ); |
| 44 |
|
| 45 |
if ( ! $headers ) { |
| 46 |
return $csv_data; |
| 47 |
} |
| 48 |
|
| 49 |
if ( $handle !== false ) { |
| 50 |
$header_count = count( $headers ); |
| 51 |
|
| 52 |
while ( ( $data = fgetcsv( $handle ) ) !== false ) { |
| 53 |
$row = []; |
| 54 |
|
| 55 |
for ( $i = 0; $i < $header_count; $i++ ) { |
| 56 |
$row[$headers[$i]] = $data[$i]; |
| 57 |
} |
| 58 |
|
| 59 |
$csv_data[] = $row; |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
fclose( $handle ); |
| 64 |
|
| 65 |
return $csv_data; |
| 66 |
} |
| 67 |
} |
| 68 |
|