NaviServer - programmable web server
4.99  5.0

[ Main Table Of Contents | Table Of Contents | Keyword Index ]

ns_getcsv(n) 4.99.30 nsdb "NaviServer Module Commands"

Name

ns_getcsv - Parse CSV Files

Table Of Contents

Synopsis

Description

This command parses lines of CSV files.

COMMANDS

ns_getcsv ?-delimiter char? ?-quotechar char? ?-trim? fileid varname

Read a single tuple (line) from an open CSV file (denoted by fileid) and parse the results into the Tcl list variable named in the last argument (varname). The command returns the number of parsed fields or -1 on end of file.

OPTIONS

-delimiter char

The delimiter is the value defined for separating fields. Default: ,

-quotechar char

The quotechar is the symbol wrapping fields. It is especially needed, when the field contains a delimiter. If the field contains a quotechar, it has to be repeated (two quote characters in sequence). Default: "

-trim

Trim whitespace from unquoted fields.

EXAMPLES

Example script from regression test:

 set csvFile test.csv
 set f [open $csvFile]
 
 while {1} {
     set r [ns_getcsv -trim $f line]
     switch $r {
         -1       {break}
          0       {}
          default {lappend lines $line}
     }
 }
 close $f
 set lines

Result:

{aaa bbb ccc} {aaa {b
bb} ccc} {zzz yyy xxx} {1 2 3} {includes(\")quote {quoted includes (") quote}} {elm2 {} empty} single {last3 empty {} {} {}}}

sample.cvs

"aaa","bbb","ccc"
"aaa","b
bb","ccc" 
zzz,yyy,xxx
 1 , 2 , 3 
includes(")quote,"quoted includes ("") quote" 
elm2,,empty
single
last3,empty,,,

See Also

ns_db

Keywords

csv, escape, quote