Skip to content

Core\Csv

Reads CSV text into rows of strings, and writes rows back as CSV. It can use a header row, and a different separator or quote character.

Core\Csv::parse reads a whole document into array<array<string>> — every field is a string, quoted fields and embedded newlines included. With { header: true } the first record is consumed as column names and every row is keyed by them; without it a row's keys are "0", "1", …. format writes each row by its values in order (its keys are ignored), quotes a field only where a byte would change the parse or where it starts or ends with a space, and { header: [...] } writes a first record. Each record ends with lineEnd: "\n" by default, or "\r\n". A field can be a tainted string, such as a value read from a database, and then the document is a tainted string too. The dialect options separator, quote and escape are single ASCII bytes.

Core\Csv::rows reads a large document one record at a time. You pass it the data directly: an open file, an uploaded file, Core\Request::bodyStream(), bytes, or a list or loop that gives bytes pieces. It also takes charset for data that is not UTF-8.

<?nvs
string $doc = "name,qty,note\nfig,2,ripe\nplum,10,\"a, b\"\n";
var $rows = Core\Csv::parse($doc, { header: true });
echo Core\Arr::count($rows), " rows\n";
foreach ($rows as array<string> $row) {
echo $row['name'], '=', $row['qty'], ' (', $row['note'], ")\n";
}
var $plain = Core\Csv::parse("a;b\n1;2\n", { separator: ';' });
echo $plain['1']['0'], '+', $plain['1']['1'], "\n";
array<array<string>> $out = [['fig', '2'], ['plum', 'a, b']];
echo Core\Csv::format($out, { header: ['item', 'note'] });
Output
2 rows
fig=2 (ripe)
plum=10 (a, b)
1+2
item,note
fig,2
plum,"a, b"

Members

3 members.

MemberSignature
parseparse(string $text, { separator?: string, quote?: string, escape?: string, header?: bool }): array<array<string>>
formatformat(array<array<string>> $rows, { separator?: string, quote?: string, header?: array<string>, lineEnd?: string }): string
rowsrows(Core\Bytes::Source|Core\Bytes::Chunks $source, { separator?: string, quote?: string, escape?: string, header?: bool, charset?: Core\Charset }): Core\Csv\Rows<string>