csv

RFC 4180 CSV parser and writer with headers, custom delimiters and escaping.

v1.0.0Data formatsbundledimport "csv";
Overview Installation Documentation Examples

Overview

RFC 4180 CSV parser and writer for HolyPHP with header support, custom delimiters, quoting/escaping, and associative row conversion.

bundled — works offline spreadsheet tsv rows

Quick start

import "csv";

$input = "id,name,bio\r\n1,Alice,\"Likes \"\"CSV\"\", tea\"\r\n2,Bob,Developer\r\n";

// Parse into associative rows using the first row as headers
$users = csv_parse_assoc($input);
println($users[0]["name"]); // Alice
println($users[0]["bio"]);  // Likes "CSV", tea

// Serialize back to CSV
$out = csv_stringify_assoc($users, ["id", "name", "bio"]);
println($out);

Installation

In a project

Inside a project (a folder with hphp.yaml, see Projects & packages):

hphp install csv

This adds the library to hphp.yaml, installs it into .hphp/packages/csv/ and pins the exact version in hphp.lock:

require:
  csv: "^1.0"

Use it

import "csv";

csv is bundled with the compiler, so import "csv"; also works in a single file without installing anything, and hphp install works offline.

Outside a project

hphp install csv          # for your user, shared by all scripts
hphp create myapp                 # or start a project, then: hphp install csv
Packagecsv
Version1.0.0 (follows the compiler)
Entry filecsv.hphp
Sourcepackages/lib/csv ↗

Documentation

API Reference

csv_parse(string $input, string $delimiter = ",", string $quote = "\""): array

Parses a CSV string into a 2D array of string fields.

csv_parse_assoc(string $input, string $delimiter = ",", string $quote = "\""): array

Parses a CSV string using the first row as header keys and returns an array of associative arrays.

csv_stringify(array $rows, string $delimiter = ",", string $quote = "\"", string $newline = "\r\n", bool $quoteAll = false): string

Serializes a 2D array of scalar values (string, int, float, bool, null) into a CSV string.

csv_stringify_assoc(array $rows, array $headers = [], string $delimiter = ",", string $quote = "\"", string $newline = "\r\n", bool $quoteAll = false): string

Serializes an array of associative arrays into a CSV string with a header row.

Error Handling

All functions validate their inputs and throw Exception with clear, csv:-prefixed messages:

Examples

01Quick start

Bundled with the compiler — import "csv"; works offline in any file, or add it to a project with hphp install csv.

import "csv";

$input = "id,name,bio\r\n1,Alice,\"Likes \"\"CSV\"\", tea\"\r\n2,Bob,Developer\r\n";

// Parse into associative rows using the first row as headers
$users = csv_parse_assoc($input);
println($users[0]["name"]); // Alice
println($users[0]["bio"]);  // Likes "CSV", tea

// Serialize back to CSV
$out = csv_stringify_assoc($users, ["id", "name", "bio"]);
println($out);
Try it
hphp install csv
hphp run main.hphp

Covered by the official test suite in tests/positive/lib_csv.hphp.