fgetcsv / fputcsv
fgetcsv(resource $stream, ?int $length = null, string $separator = ",", string $enclosure = "\"", string $escape = "\\"): array|false — fputcsv(resource $stream, array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\", string $eol = "\n"): int|false
The CSV read/write pair: fputcsv writes with RFC 4180 quoting rules and fgetcsv parses back; escape must be passed explicitly since 8.4 (empty string recommended); the quoted-comma/newline/doubled-quote traps are shown with an in-memory round trip.
C C23
#include <stdio.h>
#include <string.h>
/* the classic quoted-field state machine over a fixed CSV text */
int main(void) {
const char *csv = "name,city\n\"Alice\",\"Beijing, China\"\n\"Bob\",\"say \"\"hi\"\"\"";
char cur[128] = "", keep1[128] = "", keep2[128] = "";
int in_q = 0, row = 1, col = 1, rows = 0, pending = 0;
size_t n = 0;
for (const char *p = csv; ; p++) {
char c = *p;
int at_end = (c == '\0');
if (at_end || (!in_q && (c == ',' || c == '\n'))) {
cur[n] = '\0';
if (row == 2 && col == 2) strcpy(keep1, cur);
if (row == 3 && col == 2) strcpy(keep2, cur);
n = 0;
int had_pending = pending;
pending = 0;
if (at_end) {
if (had_pending) rows++; /* flush the last record */
break;
}
if (c == ',') col++;
else { row++; col = 1; rows++; }
} else if (c == '"') {
if (in_q && p[1] == '"') { cur[n++] = '"'; p++; pending = 1; } /* "" -> " */
else { in_q = !in_q; pending = 1; }
} else {
cur[n++] = c;
pending = 1;
}
}
printf("%d rows\n", rows);
printf("%s\n", keep1);
printf("%s\n", keep2);
return 0;
}
3 rows Beijing, China say "hi"
C++ C++26
#include <iostream>
#include <string>
#include <vector>
int main() {
const std::string csv = "name,city\n\"Alice\",\"Beijing, China\"\n\"Bob\",\"say \"\"hi\"\"\"";
std::vector<std::vector<std::string>> out;
std::vector<std::string> row;
std::string field;
bool inQ = false;
for (size_t i = 0; i < csv.size(); i++) {
char c = csv[i];
if (inQ) {
if (c == '"') {
if (i + 1 < csv.size() && csv[i + 1] == '"') { field += '"'; i++; } // "" -> "
else inQ = false;
} else field += c;
} else if (c == '"') inQ = true;
else if (c == ',') { row.push_back(field); field.clear(); }
else if (c == '\n') { row.push_back(field); field.clear(); out.push_back(row); row.clear(); }
else field += c;
}
if (!field.empty() || !row.empty()) { // flush the last record
row.push_back(field);
out.push_back(row);
}
std::cout << out.size() << " rows\n";
std::cout << out[1][1] << "\n";
std::cout << out[2][1] << "\n";
std::cout << out[0][0] << "," << out[0][1] << "\n";
return 0;
}
3 rows Beijing, China say "hi" name,city
C# v11.0.100
var rows = new List<List<string>>
{
new() { "name", "city" },
new() { "Alice", "Beijing, China" },
new() { "Bob", "say \"hi\"" },
};
string WriteCsv(List<List<string>> rs) =>
string.Join("\n", rs.Select(r => string.Join(",", r.Select(f =>
f.Contains(',') || f.Contains('"') ? "\"" + f.Replace("\"", "\"\"") + "\"" : f))));
List<List<string>> ParseCsv(string text)
{
var out_ = new List<List<string>>();
var row = new List<string>();
var field = new System.Text.StringBuilder();
var inQ = false;
for (var i = 0; i < text.Length; i++)
{
var c = text[i];
if (inQ)
{
if (c == '"')
{
if (i + 1 < text.Length && text[i + 1] == '"') { field.Append('"'); i++; } // "" -> "
else inQ = false;
}
else field.Append(c);
}
else if (c == '"') inQ = true;
else if (c == ',') { row.Add(field.ToString()); field.Clear(); }
else if (c == '\n') { row.Add(field.ToString()); field.Clear(); out_.Add(row); row = new List<string>(); }
else field.Append(c);
}
if (field.Length > 0 || row.Count > 0) { row.Add(field.ToString()); out_.Add(row); }
return out_;
}
var back = ParseCsv(WriteCsv(rows));
Console.WriteLine(back.Count + " rows");
Console.WriteLine(back[1][1]);
Console.WriteLine(back[2][1]);
Console.WriteLine(string.Join(",", back[0]));
3 rows Beijing, China say "hi" name,city
Go v1.27.4
package main
import (
"bytes"
"encoding/csv"
"fmt"
)
func main() {
rows := [][]string{{"name", "city"}, {"Alice", "Beijing, China"}, {"Bob", `say "hi"`}}
var buf bytes.Buffer
w := csv.NewWriter(&buf)
w.WriteAll(rows) // RFC 4180 quoting by default
r := csv.NewReader(bytes.NewReader(buf.Bytes()))
back, _ := r.ReadAll()
fmt.Println(len(back), "rows")
fmt.Println(back[1][1])
fmt.Println(back[2][1])
fmt.Println(back[0])
}
3 rows Beijing, China say "hi" [name city]
Java v27.0.1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
// a minimal RFC 4180 writer: quote any field containing , " or newline
static String writeCsv(List<List<String>> rows) {
StringBuilder sb = new StringBuilder();
for (List<String> row : rows) {
for (int i = 0; i < row.size(); i++) {
if (i > 0) sb.append(',');
String f = row.get(i);
if (f.contains(",") || f.contains("\"") || f.contains("\n")) {
sb.append('"').append(f.replace("\"", "\"\"")).append('"');
} else sb.append(f);
}
sb.append('\n');
}
return sb.toString();
}
// the matching quoted-field state machine
static List<List<String>> parseCsv(String text) {
List<List<String>> out = new ArrayList<>();
List<String> row = new ArrayList<>();
StringBuilder field = new StringBuilder();
boolean inQ = false;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (inQ) {
if (c == '"') {
if (i + 1 < text.length() && text.charAt(i + 1) == '"') { field.append('"'); i++; } // "" -> "
else inQ = false;
} else field.append(c);
} else if (c == '"') inQ = true;
else if (c == ',') { row.add(field.toString()); field.setLength(0); }
else if (c == '\n') { row.add(field.toString()); field.setLength(0); out.add(new ArrayList<>(row)); row.clear(); }
else field.append(c);
}
return out;
}
public static void main(String[] args) {
List<List<String>> rows = Arrays.asList(
Arrays.asList("name", "city"),
Arrays.asList("Alice", "Beijing, China"),
Arrays.asList("Bob", "say \"hi\"")
);
List<List<String>> back = parseCsv(writeCsv(rows));
System.out.println(back.size() + " rows");
System.out.println(back.get(1).get(1));
System.out.println(back.get(2).get(1));
System.out.println(back.get(0));
}
}
3 rows Beijing, China say "hi" [name, city]
JavaScript v26.13.1
// JS has no CSV in stdlib: a minimal RFC 4180 writer/parser pair
const rows = [["name", "city"], ["Alice", "Beijing, China"], ["Bob", 'say "hi"']];
function writeCsv(rs) {
return rs.map((r) => r.map((f) => /[",\n]/.test(f) ? '"' + f.replace(/"/g, '""') + '"' : f).join(",")).join("\n");
}
function parseCsv(text) {
const out = [], row = [];
let field = "", inQ = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (inQ) {
if (c === '"') {
if (text[i + 1] === '"') { field += '"'; i++; } // "" -> "
else inQ = false;
} else field += c;
} else if (c === '"') inQ = true;
else if (c === ",") { row.push(field); field = ""; }
else if (c === "\n") { row.push(field); field = ""; out.push(row.splice(0)); }
else field += c;
}
if (field !== "" || row.length) { row.push(field); out.push(row); }
return out;
}
const back = parseCsv(writeCsv(rows));
console.log(back.length + " rows");
console.log(back[1][1]);
console.log(back[2][1]);
console.log(JSON.stringify(back[0]));
3 rows Beijing, China say "hi" ["name","city"]
PHP v8.6.0
// Since PHP 8.4 the escape default is deprecated: pass it explicitly.
// The empty string disables PHP's proprietary backslash escaping (RFC 4180).
$rows = [["name", "city"], ["Alice", "Beijing, China"], ["Bob", 'say "hi"']];
$h = fopen("php://memory", "w+");
foreach ($rows as $r) {
fputcsv($h, $r, ",", "\"", "");
}
rewind($h);
$roundtrip = [];
while (($f = fgetcsv($h, null, ",", "\"", "")) !== false) {
$roundtrip[] = $f;
}
fclose($h);
echo count($roundtrip), " rows\n";
echo $roundtrip[1][1], "\n"; // the quoted comma survived
echo $roundtrip[2][1], "\n"; // doubled quotes read back as plain quotes
echo json_encode($roundtrip[0]), "\n";
3 rows Beijing, China say "hi" ["name","city"]
Python v3.15.2
import csv
import io
# the csv module is native: StringIO plays the role of PHP's php://memory
rows = [["name", "city"], ["Alice", "Beijing, China"], ["Bob", 'say "hi"']]
buf = io.StringIO()
csv.writer(buf).writerows(rows)
buf.seek(0)
back = list(csv.reader(buf))
print(len(back), "rows")
print(back[1][1])
print(back[2][1])
print(back[0])
3 rows Beijing, China say "hi" ['name', 'city']
Rust v1.99.1
fn write_csv(rows: &[Vec<&str>]) -> String {
let mut out = String::new();
for row in rows {
for (i, f) in row.iter().enumerate() {
if i > 0 {
out.push(',');
}
if f.contains([',', '"', '\n']) {
out.push('"');
out.push_str(&f.replace('"', "\"\""));
out.push('"');
} else {
out.push_str(f);
}
}
out.push('\n');
}
out
}
fn parse_csv(text: &str) -> Vec<Vec<String>> {
let mut out = Vec::new();
let mut row: Vec<String> = Vec::new();
let mut field = String::new();
let mut in_q = false;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if in_q {
if c == '"' {
if chars.peek() == Some(&'"') {
field.push('"');
chars.next();
} else {
in_q = false; // closing quote
}
} else {
field.push(c);
}
} else if c == '"' {
in_q = true;
} else if c == ',' {
row.push(std::mem::take(&mut field));
} else if c == '\n' {
row.push(std::mem::take(&mut field));
out.push(std::mem::take(&mut row));
} else {
field.push(c);
}
}
out
}
fn main() {
let rows = vec![
vec!["name", "city"],
vec!["Alice", "Beijing, China"],
vec!["Bob", "say \"hi\""],
];
let back = parse_csv(&write_csv(&rows));
println!("{} rows", back.len());
println!("{}", back[1][1]);
println!("{}", back[2][1]);
println!("{:?}", back[0]);
}
3 rows Beijing, China say "hi" ["name", "city"]
TypeScript v26.13.1
// Same runtime as the hand-written JS pair, with row typing
const rows: string[][] = [["name", "city"], ["Alice", "Beijing, China"], ["Bob", 'say "hi"']];
function writeCsv(rs: string[][]): string {
return rs.map((r) => r.map((f: string) => /[",\n]/.test(f) ? '"' + f.replace(/"/g, '""') + '"' : f).join(",")).join("\n");
}
function parseCsv(text: string): string[][] {
const out: string[][] = [], row: string[] = [];
let field = "", inQ = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (inQ) {
if (c === '"') {
if (text[i + 1] === '"') { field += '"'; i++; } // "" -> "
else inQ = false;
} else field += c;
} else if (c === '"') inQ = true;
else if (c === ",") { row.push(field); field = ""; }
else if (c === "\n") { row.push(field); field = ""; out.push(row.splice(0)); }
else field += c;
}
if (field !== "" || row.length) { row.push(field); out.push(row); }
return out;
}
const back = parseCsv(writeCsv(rows));
console.log(back.length + " rows");
console.log(back[1][1]);
console.log(back[2][1]);
console.log(JSON.stringify(back[0]));
3 rows Beijing, China say "hi" ["name","city"]
Language differences
C: no stdlib CSV — the classic quoted-field state machine: " enters in-quote state, "" inside quotes is an escaped quote, and commas inside quotes are not separators; the example parses a fixed text byte by byte and captures the target fields.
C++: same state-machine idea as C with std::string; production code uses third-party parsers like fast-cpp-csv-parser.
C#: no CSV in stdlib — the same hand-written state machine (CsvHelper in production); fields accumulate in a StringBuilder.
Go: native encoding/csv — Writer.WriteAll / Reader.ReadAll are RFC 4180-style by default (quote doubling) with no escape parameter to worry about.
Java: no CSV in stdlib (the naive String.split cannot handle quoted fields) — hand-written state machine; production uses Commons CSV / univocity.
JavaScript: no CSV in stdlib — the example hand-writes a minimal RFC 4180 writer + parser; newlines/commas inside quotes are CSV's classic trap and demand a state machine, never split(",").
PHP: relying on the escape default is deprecated since 8.4 — pass it explicitly (positionally or as a named argument), with the empty string "" recommended (fully disables PHP's proprietary backslash escaping so output is RFC 4180-compliant and round-trips losslessly); " is not special inside quotes, doubling "" is the standard escape; fputcsv gained the $eol parameter in 8.1; a blank line reads back as [null]; the locale's LC_CTYPE affects parsing of some single-byte encodings.
Python: native csv module — csv.writer/csv.reader default to the standard doubling semantics; a StringIO round trip mirrors PHP's php://memory.
Rust: no CSV in stdlib — the example hand-writes the state machine; production uses the csv crate (Serde integration included).
TypeScript: same runtime as the hand-written JS pair.