diff options
Diffstat (limited to 'it_pipe.class')
-rw-r--r-- | it_pipe.class | 14 |
1 files changed, 10 insertions, 4 deletions
diff --git a/it_pipe.class b/it_pipe.class index 084e03d..d3e4ae0 100644 --- a/it_pipe.class +++ b/it_pipe.class @@ -195,6 +195,7 @@ function cols($collist, $separator = "\t") * Return contents of pipe as associative records. Column titles read from first line, separators can be \t or ; or , * @param $p['forceschema'] ignore schema in file, replace it with this comma separated column list * @param $p['fixcolnames'] replace non-identifier chars in colum names + * @param $p['it_error'] error params */ function csv($p = []) { @@ -202,15 +203,20 @@ function csv($p = []) $counts = count_chars($this->lines[0]); $splitchar = $counts[ord("\t")] ? "\t" : ($counts[ord(";")] > $counts[ord(",")] ? ";" : ","); $csvhead = it::replace(['^\x{FEFF}' => ''], array_shift($this->lines)); // it::replace removes utf8 byte order mark - $cols = $p['forceschema'] ? explode(",", $p['forceschema']) : str_getcsv(trim($csvhead, "#\n "), $splitchar, '"'); # should function_exists('str_getcsv') - foreach ($cols as $idx => $col) - $cols[$idx] = it::replace(['^$' => "field$idx", '\W' => $p['fixcolnames'] ? "_" : '$0'], $col); + $schema = $p['forceschema'] ? explode(",", $p['forceschema']) : str_getcsv(trim($csvhead, "#\n "), $splitchar, '"'); # should function_exists('str_getcsv') + foreach ($schema as $idx => $col) + $schema[$idx] = it::replace(['^$' => "field$idx", '\W' => $p['fixcolnames'] ? "_" : '$0'], $col); $oldlocale = setlocale(LC_CTYPE, "0"); setlocale(LC_CTYPE, 'de_CH.iso-8859-1'); # this works for utf-8 as well foreach ($this->lines as $line) - $records[] = (object)(($t = array_combine($cols, $t2 = str_getcsv($line, $splitchar, '"'))) ? $t : it::error("schema mismatch: " . count($cols) . " vs " . count($t2))); # NOPHPLINT + { + if (($cols = str_getcsv($line, $splitchar, '"')) && count($schema) == count($cols)) + $records[] = (object)array_combine($schema, $cols); + else + it::error((array)$p['it_error'] + ['title' => "schema mismatch: " . count($schema) . " vs " . count($cols), 'body' => [$schema, $line]]); # NOPHPLINT + } setlocale(LC_CTYPE, $oldlocale); |