77 * Enhanced CSV file object
88 */
99class CsvFile extends File implements \Countable {
10- private $ file_path ;
10+ const DEFAULT_ENCODING = ' utf-8 ' ;
1111private $ encoding = 'utf-8 ' ;
1212private $ is_head_row = false ;
1313/**
@@ -20,17 +20,16 @@ class CsvFile extends File implements \Countable {
2020private $ start_column = 0 ;
2121private $ columns_to_skip = array ();
2222
23- function __construct ($ file_path , $ delimiter = ', ' , $ enclosure = '" ' , $ escape = "\\" ) {
24- if (!file_exists ($ file_path )) {
25- throw new Exception ("File $ file_path does not exist. " );
23+ function __construct ($ file , $ delimiter = ', ' , $ enclosure = '" ' , $ escape = "\\" ) {
24+ if (!file_exists ($ file )) {
25+ throw new Exception ("File $ file does not exist. " );
2626}
2727
28- if (filesize ($ file_path ) === 0 ) {
28+ if (filesize ($ file ) === 0 ) {
2929throw new Exception ("Empty file. " );
3030}
3131
32- $ this ->file_path = $ file_path ;
33- parent ::__construct ($ file_path , 'r ' );
32+ parent ::__construct ($ file , 'r+ ' );
3433$ this ->setFlags (File::READ_CSV | File::READ_AHEAD | File::SKIP_EMPTY | File::DROP_NEW_LINE );
3534$ this ->setCsvControl ($ delimiter , $ enclosure , $ escape );
3635}
@@ -43,6 +42,10 @@ function count() {
4342return count ($ this ->to_array ());
4443}
4544
45+ function set_encoding ($ encoding ) {
46+ $ this ->encoding = $ encoding ;
47+ }
48+
4649public function to_array () {
4750$ rows = [];
4851foreach ($ this as $ row ) {
@@ -93,7 +96,14 @@ private function remove_columns($old_row) {
9396return $ new_row ;
9497}
9598
99+ function convert_to_default_encoding ($ val ) {
100+ return mb_convert_encoding ($ val , static ::DEFAULT_ENCODING , $ this ->encoding );
101+ }
102+
96103private function format_row ($ row ) {
104+ if ($ this ->encoding !== static ::DEFAULT_ENCODING ) {
105+ $ row = array_map ([$ this , 'convert_to_default_encoding ' ], $ row );
106+ }
97107$ row = array_combine (
98108$ this ->get_column_names ($ row ),
99109$ row
0 commit comments