summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--it_pipe.class14
-rwxr-xr-xtests/it_pipe.t10
2 files changed, 14 insertions, 10 deletions
diff --git a/it_pipe.class b/it_pipe.class
index 2c5a184..737908a 100644
--- a/it_pipe.class
+++ b/it_pipe.class
@@ -156,20 +156,22 @@ function cols($collist, $separator = "\t")
}
/**
- * Return contents of pipe as associative records
+ * Return contents of pipe as associative records. Column titles read from first line, separators can be \t or ; or ,
+ * @param $forceschema ignore schema in file, replace it with this comma separated column list
*/
-function csv()
+function csv($forceschema = null)
{
$counts = count_chars($this->lines[0]);
$splitchar = $counts[ord("\t")] ? "\t" : ($counts[ord(";")] > $counts[ord(",")] ? ";" : ",");
- $schema = str_getcsv(trim(array_shift($this->lines), "#\n "), $splitchar, '"'); # could do a function_exists('str_getcsv') here...
- foreach (preg_grep('/^$/', $schema) as $idx => $dummy)
- $schema[$idx] = "field$idx";
+ $csvhead = array_shift($this->lines);
+ $cols = $forceschema ? explode(",", $forceschema) : str_getcsv(trim($csvhead, "#\n "), $splitchar, '"'); # should function_exists('str_getcsv')
+ foreach (preg_grep('/^$/', $cols) as $idx => $dummy)
+ $cols[$idx] = "field$idx"; # replace empty column names
$oldlocale = setlocale(LC_CTYPE, 'de_CH.iso-8859-1'); # this works for utf-8 as well
foreach ($this->lines as $line)
- $records[] = (object)array_combine($schema, str_getcsv($line, $splitchar, '"')); # could do a function_exists('str_getcsv') here...
+ $records[] = (object)array_combine($cols, str_getcsv($line, $splitchar, '"')); # could do a function_exists('str_getcsv') here...
setlocale(LC_CTYPE, $oldlocale);
diff --git a/tests/it_pipe.t b/tests/it_pipe.t
index c65073d..ce55469 100755
--- a/tests/it_pipe.t
+++ b/tests/it_pipe.t
@@ -1,7 +1,9 @@
#!/www/server/bin/php
<?php
-is(json_encode((new it_pipe('data' => array("a\tb", "1\t2")))->csv()), '[{"a":"1","b":"2"}]', "it_pipe::csv()");
-is(json_encode((new it_pipe('data' => array("a;b", "1;2")))->csv()), '[{"a":"1","b":"2"}]', "it_pipe::csv()");
-is(json_encode((new it_pipe('data' => array("a,b", "1,2")))->csv()), '[{"a":"1","b":"2"}]', "it_pipe::csv()");
-is(json_encode((new it_pipe('data' => array("a\tb", "1\t2")))->csv("c,d")), '[{"c":"1","d":"2"}]', "it_pipe::csv()");
+# csv()
+is(json_encode((new it_pipe('data' => array("a\tb", "1\t2")))->csv()), '[{"a":"1","b":"2"}]', "it_pipe::csv()");
+is(json_encode((new it_pipe('data' => array("a;b", "1;2")))->csv()), '[{"a":"1","b":"2"}]', "it_pipe::csv()");
+is(json_encode((new it_pipe('data' => array("a,b", "1,2")))->csv()), '[{"a":"1","b":"2"}]', "it_pipe::csv()");
+is(json_encode((new it_pipe('data' => array("a\tb", "1\t2")))->csv("c,d")), '[{"c":"1","d":"2"}]', "it_pipe::csv()");
+is(json_encode((new it_pipe('data' => array("\t", "1\t2")))->csv()), '[{"field0":"1","field1":"2"}]', "it_pipe::csv()");