[PHP-DEV] [RFC] CSV Extension (ext/csv)

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

On Fri, Oct 9, 2026 at 8:22 AM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

I see that there’s no support for open streams/resources, would that be something worth adding? I don’t want to have to write things to a file before I can start processing them if I already have an open stream. Same goes for reading, I don’t want to have to read everything before passing it somewhere, often having it as a resource is more useful to me.

About LazyLaxCollection, what does Lax mean here?

Hi,
Thanks for the feedback! Both are good points.

On streams/resources:
I agree that supporting already-open streams would be a valuable addition, particularly for reading. For writing, it is already possible to stream rows individually without buffering the entire collection:

foreach ($rows as $row) {
fwrite($stream, Csv\array_to_row($row));
}

However, a dedicated collection_to_stream() would provide a more convenient API, consistent row-width validation, and symmetry with the existing file-based function. For reading, the gap is more significant. Splitting a stream into lines and passing them to row_to_array() is not reliable because enclosed CSV fields may contain line breaks. The parser used by createFromFile() already operates on PHP streams internally, so exposing this functionality for existing stream resources should be relatively straightforward. I’m considering two additional entry points:

Csv\collection_to_stream($stream, iterable $collection, …): void
Csv\LazyLaxCollection::createFromStream($stream, …): LazyLaxCollection

I would prefer separate entry points rather than overloading the existing $file parameter to accept both paths and resources. Since PHP does not support resource as a declared parameter type, the stream parameter would be untyped, documented as @param resource, and validated at runtime, with invalid arguments resulting in a TypeError.

The intended semantics for createFromStream() would be:

  • Parsing starts at the stream’s current position, allowing callers to skip a BOM or preamble beforehand.
  • The extension borrows the stream and never closes it.
  • Repeated iteration seeks back to the position recorded when the collection was created. Non-seekable streams support only a single iteration.
  • If the caller closes the stream during iteration, subsequent reads should throw an error rather than access freed memory.
  • Since the parser reads ahead in chunks, the underlying stream’s position after partial iteration is not guaranteed to match the end of the last returned row. Mixing reads from the collection with direct reads from the same stream would therefore not be supported.
    Would these semantics work for your use cases, particularly the read-ahead behavior and separate entry points?

On LazyLaxCollection:

“Lax” means that rows are not required to contain the same number of fields. This mirrors the distinction between buffer_to_collection(), which throws a ValueError when row widths differ, and buffer_to_collection_lax(), which accepts rows of varying widths. The name comes from the original girgias/csv implementation by Gina Peter Banyard. To make this behavior explicit, I’ve also added a dedicated PHPT test: ext/csv/tests/LazyCollection/fromBuffer/lax_varying_field_count.phpt. The test verifies that LazyLaxCollection::createFromBuffer() accepts consecutive rows containing 3, 1, 2, and 4 fields, while buffer_to_collection() throws a ValueError for the same input. Naming is already listed as an open issue in the RFC, along with whether a strict lazy variant should be included. Your question reinforces that the current name may not communicate its purpose clearly enough. I’d welcome suggestions here. For example, LazyCollection with configurable strictness could be worth considering. I’ll update the RFC once we’ve had a chance to discuss the API details.

Thanks again!

Best regards,
Damian

On Fri, Oct 9, 2026 at 9:03 AM Lynn <kjarli@gmail.com> wrote:

On Fri, Oct 9, 2026 at 8:22 AM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

I see that there’s no support for open streams/resources, would that be something worth adding? I don’t want to have to write things to a file before I can start processing them if I already have an open stream. Same goes for reading, I don’t want to have to read everything before passing it somewhere, often having it as a resource is more useful to me.

About LazyLaxCollection, what does Lax mean here?

This RFC led me to take a closer look at the built-in CSV functions, and what I found makes me favor a different path to the same goals.

The RFC argues that their behavior “cannot be fixed without breaking compatibility”. I went through the list:

  • $escape: already addressed by the PHP 8.4 deprecation; the default changes to “” in PHP 9.0.

  • Locale dependence: php/php-src#24207 (https://github.com/php/php-src/pull/24207, under review, prompted by this RFC) removes the per-byte libc lookup for ASCII characters in ASCII-compatible locales. The remaining isspace() before an opening enclosure can be replaced with an explicit space/tab check. For non-ASCII bytes in CJK locales, mbrlen() serves a purpose: a Shift_JIS character can contain a ‘|’ trail byte without that byte being a delimiter. A locale-independent byte parser would split it.

  • Single-byte delimiters and enclosures: longer values currently throw ValueError, so support for multibyte tokens can be added without changing existing valid calls.

  • No inverse of str_getcsv(): a str_putcsv() function would fill that gap and let SplFileObject::fputcsv() callers use $file->fwrite(str_putcsv($row)).

  • [null] for an empty line and whitespace before an enclosure: these can be addressed by an opt-in strict mode without changing the default behavior. Enclosing fields containing spaces on output is permitted by RFC 4180 section 2.5 and is not a compliance defect.

Strict validation, multibyte tokens, string serialization and lazy reading can all be built on the existing API. Lazy iteration over a stream already works with a generator around fgetcsv(); strict row-width validation can be layered on top. These changes can be developed and reviewed independently, without replacing the parser or breaking existing calls.

I have benchmarks and test scripts for the existing implementation and the proposed extension here: https://github.com/ArtUkrainskiy/php-src-bench/tree/main/reports/csv-pr-24199

Adding ext/csv instead would leave core maintaining two independent CSV parsers for the foreseeable future. The RFC explicitly leaves the built-ins unchanged, and the June discussion around the SplFileObject deprecations showed understandable reluctance to remove existing APIs without an established migration path (https://news-web.php.net/php.internals/131503, and the August follow-up: https://news-web.php.net/php.internals/132186).

The branch itself is in good shape. The issues I reported on the PR were addressed quickly, and the parser is now faster than fgetcsv() in my benchmarks. This is not an objection to the implementation or the work that went into it.

My concern is the long-term maintenance cost of introducing a second parser when the existing one can be improved incrementally. I’d rather help land those improvements in ext/standard.

пт, 9 окт. 2026 г. в 17:07, Damian Jóźwiak <damian.jozwiak.lodz@gmail.com>:

···

Best regards,
Artem Ukrainskiy

Hi everyone,

Thank you for the feedback, and Artem, for the detailed review and independent verification of the implementation.

I think the discussion has raised two important questions: whether these improvements belong in the existing CSV API or a dedicated extension, and what an API supporting both files and already-open streams should look like.

Artem, your point about incremental improvements is fair. The RFC’s statement that the existing behaviour “cannot be fixed without breaking compatibility” is too broad. Several improvements could be introduced through additional functions or opt-in behaviour while preserving existing calls. You are also right that enclosing fields containing spaces is permitted by RFC 4180, and that locale-independent byte parsing has different implications for encodings such as Shift_JIS.

At the same time, PHP has taken the approach of introducing a modern API alongside an established one when their contracts differ substantially. The new DOM API, including Dom\Document, coexists with the legacy DOMDocument API, and the URI extension provides a dedicated API alongside parse_url(). These are relevant precedents for giving users clearer semantics without changing the behaviour of existing applications. Of course, those precedents do not automatically justify another CSV parser. They do suggest that improving the existing API and introducing a dedicated one are both reasonable approaches to evaluate. The question is whether the consistency and usability of the proposed CSV API justify its maintenance cost.

My motivation is to provide parsing, serialization, validation and file handling with consistent, explicit defaults. In particular, the file-based entry points accept a path and manage the underlying stream, covering the convenience previously provided by SplFileObject’s CSV methods. The existing fgetcsv()/fputcsv() functions operate on streams supplied by the caller. Both use cases deserve support.

Separately, the remaining overlapping-token writer issue reported on the PR has been addressed in https://github.com/php/php-src/commit/b7866156dc7e77304fe3419edceba6f890b113cb. Fields are now enclosed when tokens could form across field/separator boundaries. Distinguishable overlapping dialects remain supported; ambiguous combinations such as delimiter xy with enclosure xyx are rejected by both readers and writers. Regression tests cover both behaviours, and all 92 PHPT tests pass in my local verification.

With those concerns in mind, I would like to discuss three possible directions:

A. Improve the existing API in ext/standard, adding capabilities such as string serialization, multibyte tokens and opt-in strict parsing, with file and lazy-reading conveniences considered where needed.

B. Continue with the dedicated ext/csv proposal, retaining its function-based API and lazy collection, while adding entry points for existing streams and resolving the naming questions.

C. Rework the proposal around an object-oriented API in the Csv namespace, with explicit file and stream factories and writing methods. Stream ownership, iteration, validation and string conversion would need to be specified before this became a concrete voting option.

My preference remains a dedicated API with consistent semantics, but I am open to revising its shape or pursuing the existing-API route if that is the direction the project prefers.

Would a directional vote between these approaches be useful if discussion does not establish a clear preference? I would first document the alternatives and their trade-offs, and agree on the voting format. Selecting a direction would guide a revised proposal; it would not approve an API whose details have yet to be reviewed.

The current RFC does not propose deprecating the existing CSV functions. Any future consolidation would need its own discussion and an established migration path, rather than assuming that introducing a new API commits PHP to removing the old one.

The goal is to establish a maintainable CSV path for PHP users, including those migrating from the deprecated SplFileObject methods. I would welcome your thoughts on which direction best serves that goal.

Best regards,
Damian

···

Best regards,
Artem Ukrainskiy

Hi internals,

The discussion for this RFC started on October 9, and there has been no further feedback on the mailing list or GitHub for approximately two weeks.

Unless any new concerns or objections are raised, I intend to open the vote on November 2.

Thanks to everyone who participated in the discussion.

Best regards,
Damian

···

Best regards,
Artem Ukrainskiy

Hi

On 10/26/26 15:52, Damian Jóźwiak wrote:

The discussion for this RFC started on October 9, and there has been no
further feedback on the mailing list or GitHub for approximately two weeks.

within those two weeks there was last week’s security release. As with the Io\Terminal RFC, I suggest to wait with the vote until things have calmed down.

See also: php.internals: Re: [RFC] Io\Terminal

Unless any new concerns or objections are raised, I intend to open the vote
on November 2.

I did not have the time to read the RFC due to the above, but one big concern of mine is the choice of namespace. I'm not sure if “CSV” is an important and large enough topic to warrant its own core extension and to reserve another top-level namespace. There might be a way to nicely group it with something else (e.g. “file format” or ”serialization format”) and I believe that warrants further discussion and opinion.

I'd also like to hear from Gina as the original author of the extension you propose for inclusion in core.

Best regards
Tim Düsterhus

Hi Tim,

Thanks for your feedback.

You’re right about the timing. I hadn’t fully considered the impact of last week’s security release on the availability of contributors. I’m happy to postpone the vote to allow more time for discussion.

Regarding the namespace, I see your point. I chose “Csv” because it is simple, clearly describes the functionality, and follows a similar approach to existing namespaces such as “Uri” and “Dom”. However, I’m open to discussing alternative approaches if a broader naming convention would make more sense for PHP.

I also agree that hearing from Gina would be valuable.

Thanks again for taking the time to share your concerns.

Best regards,
Damian

pon., 26 paź 2026, 23:05 użytkownik Tim Düsterhus <tim@bastelstu.be> napisał:

Hi

On 10/26/26 15:52, Damian Jóźwiak wrote:

The discussion for this RFC started on October 9, and there has been no
further feedback on the mailing list or GitHub for approximately two weeks.

within those two weeks there was last week’s security release. As with
the Io\Terminal RFC, I suggest to wait with the vote until things have
calmed down.

See also: https://news-web.php.net/php.internals/132895

Unless any new concerns or objections are raised, I intend to open the vote
on November 2.
I did not have the time to read the RFC due to the above, but one big
concern of mine is the choice of namespace. I’m not sure if “CSV” is an
important and large enough topic to warrant its own core extension and
to reserve another top-level namespace. There might be a way to nicely
group it with something else (e.g. “file format” or ”serialization
format”) and I believe that warrants further discussion and opinion.

I’d also like to hear from Gina as the original author of the extension
you propose for inclusion in core.

Best regards
Tim Düsterhus

On Fri, Oct 9, 2026 at 8:22 AM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

Hi Damien,
thanks for the proposal, indeed with the deprecation of SplFileObject CSV feature an object oriented alternative is welcomed having said that.I have a couple of remarks/suggestions

  • Following Tim’s thought, I wonder if a CSV top namespace is mandatory or if we should not just have a Serialization “namespace” name that can be improved when such classes and functions are defined.

  • RFC 4180-compatible parsing and serialization by default. As much as I am a proponent of backing RFC whenever they exist in this case it should be stressed out that RFC4180 is not an accepted RFC like for instance RFC3986 for URI specification as such it is totally possible to have a valid CSV which does not comply with the refer draft specification. I believe this should be noted and explained in the RFC to avoid pushing forward something which is not a real specification as anyone would expect even though it is widely accepted as the “default” implementation,

  • Hence why I believe that using terms like lax and strict is counter productive; probably other names “to be defined” should be used instead. Maybe adding an Enum With RFC4180 and something else (?) would be a better take. Which would reduce the number of function/methods introduced ?

  • Also while it is common to talk about CSV, this feature would be perhaps better called Character Separated Value than Comma Separated Value since the delimiter can be changed. And covers TSV and other exotic formats which separates values per single character.

The stream is owned by the object: like the stream of SplFileObject, it remains visible as a resource but fclose() refuses to close it, and it is closed when the object is destroyed (for an object alive until the end of the request, while destructors run, so a user wrapper’s stream_close() is still called).

Does it mean that the LazyLaxCollection will expose the stream metadata ? If I receive in my method/function a LazyLaxCollection is it possible for me to get access to the underlying resource metadata ? To know how it is open, its pathname , and so forth ? Can I easily detect if

Being able to configure the context or to apply stream filter is also something I find useful with the current set of csv function even with SplFileObject (even though it is tricky with that one) I would expect any API which aim at replacing the current CSV API to offer at most the same extensibility or to allow it in any other shape or form.

function collection_to_file(string $file, iterable $collection, string $delimiter = ',', string $enclosure = '"', string $eolSequence = "\r\n"): void {}

Why? can’t we have access to the written bytes as returned value. Otherwise it means we need to re-access the resource afterward if we want to get access to that value. For example if we want to generate the Content-Length header or something else ?

Overall, I like the direction of the RFC but I believe some major discussion points remain unsolved before going to a vote

Best regards,
Ignace

Hi

On 2026-10-29 16:33, ignace nyamagana butera wrote:

Does it mean that the LazyLaxCollection will expose the stream metadata ?
If I receive in my method/function a LazyLaxCollection is it possible for
me to get access to the underlying resource metadata ? To know how it is
open, its pathname , and so forth ? Can I easily detect if

That paragraph appears to be cut off. Can you check?

Best regards
Tim Düsterhus

On Thu, Oct 29, 2026 at 5:16 PM Tim Düsterhus <tim@bastelstu.be> wrote:

Hi

On 2026-10-29 16:33, ignace nyamagana butera wrote:

Does it mean that the LazyLaxCollection will expose the stream metadata
?
If I receive in my method/function a LazyLaxCollection is it possible
for
me to get access to the underlying resource metadata ? To know how it
is
open, its pathname , and so forth ? Can I easily detect if

That paragraph appears to be cut off. Can you check?

Best regards
Tim Düsterhus

Indeed it was cut off I rephrased it as follow:

Does this mean that LazyLaxCollection will expose the stream metadata?

If I receive a LazyLaxCollection instance in a method or function, will I be able to access the underlying resource metadata:

  • understand how the stream was opened,
  • retrieve its pathname, and … ?
  • can I easily determine whether the underlying stream is a local file, a temporary file, a memory stream, or something else?
    These are genuine questions that someone might ask when working with an instantiated LazyLaxCollection object.

On Thu, Oct 29, 2026 at 4:30 PM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Fri, Oct 9, 2026 at 8:22 AM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

Hi Damien,
thanks for the proposal, indeed with the deprecation of SplFileObject CSV feature an object oriented alternative is welcomed having said that.I have a couple of remarks/suggestions

  • Following Tim’s thought, I wonder if a CSV top namespace is mandatory or if we should not just have a Serialization “namespace” name that can be improved when such classes and functions are defined.

  • RFC 4180-compatible parsing and serialization by default. As much as I am a proponent of backing RFC whenever they exist in this case it should be stressed out that RFC4180 is not an accepted RFC like for instance RFC3986 for URI specification as such it is totally possible to have a valid CSV which does not comply with the refer draft specification. I believe this should be noted and explained in the RFC to avoid pushing forward something which is not a real specification as anyone would expect even though it is widely accepted as the “default” implementation,

  • Hence why I believe that using terms like lax and strict is counter productive; probably other names “to be defined” should be used instead. Maybe adding an Enum With RFC4180 and something else (?) would be a better take. Which would reduce the number of function/methods introduced ?

  • Also while it is common to talk about CSV, this feature would be perhaps better called Character Separated Value than Comma Separated Value since the delimiter can be changed. And covers TSV and other exotic formats which separates values per single character.

The stream is owned by the object: like the stream of SplFileObject, it remains visible as a resource but fclose() refuses to close it, and it is closed when the object is destroyed (for an object alive until the end of the request, while destructors run, so a user wrapper’s stream_close() is still called).

Does it mean that the LazyLaxCollection will expose the stream metadata ? If I receive in my method/function a LazyLaxCollection is it possible for me to get access to the underlying resource metadata ? To know how it is open, its pathname , and so forth ? Can I easily detect if

Being able to configure the context or to apply stream filter is also something I find useful with the current set of csv function even with SplFileObject (even though it is tricky with that one) I would expect any API which aim at replacing the current CSV API to offer at most the same extensibility or to allow it in any other shape or form.

function collection_to_file(string $file, iterable $collection, string $delimiter = ',', string $enclosure = '"', string $eolSequence = "\r\n"): void {}

Why? can’t we have access to the written bytes as returned value. Otherwise it means we need to re-access the resource afterward if we want to get access to that value. For example if we want to generate the Content-Length header or something else ?

Overall, I like the direction of the RFC but I believe some major discussion points remain unsolved before going to a vote

Best regards,
Ignace

Hi Damien,

It just occurred to me that I forgot to mention one point: the RFC is missing a section defining the supported types, similar to the one included in the URI Query Parameters RFC: https://wiki.php.net/rfc/query_params#supported_types.

I believe such a section is important to avoid surprising behaviour when generating CSV data.

For instance, the current CSV implementation in PHP does not support converting objects of any kind. However, since the introduction of enums, both JSON serialization and http_build_query() support backed enums as values that can be converted. I would therefore expect backed enums to be supported by your proposal, or at the very least for this to be explicitly addressed in the RFC.

Conversely, resources are currently accepted during CSV conversion which we all agree is an unfamiliar behaviour. This RFC could therefore be a good opportunity to align CSV conversion with the new Query Params RFC (pending its acceptance) and the existing JSON conversion rules, establishing a common baseline for type conversion and serialization across PHP.

PS: I realise this is not really the focus of your RFC, but it also raises the question of whether support for backed enums should be added to PHP’s existing CSV functionality in PHP 8.7. After all, support for backed enums in http_build_query() was introduced in PHP 8.4, rather than being included when enums were first introduced.

Best regards,

Ignace

Hi Ignace,

Thank you, that’s a good catch. Writing the section showed that The RFC also contained an inconsistency between the documented behaviour and the implementation: it said unsupported fields throw a TypeError, but the implementation just did a plain string cast, exactly like fputcsv(). So arrays became “Array” with a warning, resources became “Resource id
#N” silently, and all enums threw a generic Error.

I’ve added a “Supported types” section to the RFC and updated the implementation to match. When writing, fields are converted as follows:

  • string: as is
  • null: empty field
  • bool: “1” / “0” (false used to be written as an empty field, which could not be told apart from null)
  • int: decimal representation
  • float: formatted with serialize_precision, like json_encode(). fputcsv() uses precision, so 0.1 + 0.2 was silently truncated to 0.3.
  • backed enum: its backing value
  • object convertible to string: the result of the string conversion (__toString(), or the internal cast of classes such as GMP)
  • pure enum, any other object, array, resource: TypeError

The error names the field and the row, e.g. Field “name” of element 3 of the collection must be of type null|bool|int|float|string|BackedEnum or an object convertible to string, resource given.

When reading, every field is returned as a string, with no type inference.

The one place where I deliberately diverge from the Query Params RFC is objects convertible to string. They are accepted without an explicit cast because fputcsv() and SplFileObject::fputcsv() accept them today, and this extension is meant to be the migration target for the latter. Requiring (string)
there seemed like friction without much benefit. If you see a strong reason to align fully, I’m open to changing it.

On your PS: I agree it’s worth doing, but I’ve kept it out of this RFC and listed it under Future Scope. Adding backed enum support to fputcsv() would not be a BC break, since enums currently throw there. Like the http_build_query() change in 8.4 (GH-15650, fixed via GH-15704 without an RFC), it could be
a small standalone PR for 8.7. Rejecting resources and arrays in the legacy functions, on the other hand, would be a BC break and would need a deprecation first.

Best regards,
Damian

On Tue, Nov 10, 2026 at 9:36 AM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Thu, Oct 29, 2026 at 4:30 PM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Fri, Oct 9, 2026 at 8:22 AM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

Hi Damien,
thanks for the proposal, indeed with the deprecation of SplFileObject CSV feature an object oriented alternative is welcomed having said that.I have a couple of remarks/suggestions

  • Following Tim’s thought, I wonder if a CSV top namespace is mandatory or if we should not just have a Serialization “namespace” name that can be improved when such classes and functions are defined.

  • RFC 4180-compatible parsing and serialization by default. As much as I am a proponent of backing RFC whenever they exist in this case it should be stressed out that RFC4180 is not an accepted RFC like for instance RFC3986 for URI specification as such it is totally possible to have a valid CSV which does not comply with the refer draft specification. I believe this should be noted and explained in the RFC to avoid pushing forward something which is not a real specification as anyone would expect even though it is widely accepted as the “default” implementation,

  • Hence why I believe that using terms like lax and strict is counter productive; probably other names “to be defined” should be used instead. Maybe adding an Enum With RFC4180 and something else (?) would be a better take. Which would reduce the number of function/methods introduced ?

  • Also while it is common to talk about CSV, this feature would be perhaps better called Character Separated Value than Comma Separated Value since the delimiter can be changed. And covers TSV and other exotic formats which separates values per single character.

The stream is owned by the object: like the stream of SplFileObject, it remains visible as a resource but fclose() refuses to close it, and it is closed when the object is destroyed (for an object alive until the end of the request, while destructors run, so a user wrapper’s stream_close() is still called).

Does it mean that the LazyLaxCollection will expose the stream metadata ? If I receive in my method/function a LazyLaxCollection is it possible for me to get access to the underlying resource metadata ? To know how it is open, its pathname , and so forth ? Can I easily detect if

Being able to configure the context or to apply stream filter is also something I find useful with the current set of csv function even with SplFileObject (even though it is tricky with that one) I would expect any API which aim at replacing the current CSV API to offer at most the same extensibility or to allow it in any other shape or form.

function collection_to_file(string $file, iterable $collection, string $delimiter = ',', string $enclosure = '"', string $eolSequence = "\r\n"): void {}

Why? can’t we have access to the written bytes as returned value. Otherwise it means we need to re-access the resource afterward if we want to get access to that value. For example if we want to generate the Content-Length header or something else ?

Overall, I like the direction of the RFC but I believe some major discussion points remain unsolved before going to a vote

Best regards,
Ignace

Hi Damien,

It just occurred to me that I forgot to mention one point: the RFC is missing a section defining the supported types, similar to the one included in the URI Query Parameters RFC: https://wiki.php.net/rfc/query_params#supported_types.

I believe such a section is important to avoid surprising behaviour when generating CSV data.

For instance, the current CSV implementation in PHP does not support converting objects of any kind. However, since the introduction of enums, both JSON serialization and http_build_query() support backed enums as values that can be converted. I would therefore expect backed enums to be supported by your proposal, or at the very least for this to be explicitly addressed in the RFC.

Conversely, resources are currently accepted during CSV conversion which we all agree is an unfamiliar behaviour. This RFC could therefore be a good opportunity to align CSV conversion with the new Query Params RFC (pending its acceptance) and the existing JSON conversion rules, establishing a common baseline for type conversion and serialization across PHP.

PS: I realise this is not really the focus of your RFC, but it also raises the question of whether support for backed enums should be added to PHP’s existing CSV functionality in PHP 8.7. After all, support for backed enums in http_build_query() was introduced in PHP 8.4, rather than being included when enums were first introduced.

Best regards,

Ignace

On Tue, Nov 10, 2026 at 12:07 PM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi Ignace,

Thank you, that’s a good catch. Writing the section showed that The RFC also contained an inconsistency between the documented behaviour and the implementation: it said unsupported fields throw a TypeError, but the implementation just did a plain string cast, exactly like fputcsv(). So arrays became “Array” with a warning, resources became “Resource id
#N” silently, and all enums threw a generic Error.

I’ve added a “Supported types” section to the RFC and updated the implementation to match. When writing, fields are converted as follows:

  • string: as is
  • null: empty field
  • bool: “1” / “0” (false used to be written as an empty field, which could not be told apart from null)
  • int: decimal representation
  • float: formatted with serialize_precision, like json_encode(). fputcsv() uses precision, so 0.1 + 0.2 was silently truncated to 0.3.
  • backed enum: its backing value
  • object convertible to string: the result of the string conversion (__toString(), or the internal cast of classes such as GMP)
  • pure enum, any other object, array, resource: TypeError

The error names the field and the row, e.g. Field “name” of element 3 of the collection must be of type null|bool|int|float|string|BackedEnum or an object convertible to string, resource given.

When reading, every field is returned as a string, with no type inference.

The one place where I deliberately diverge from the Query Params RFC is objects convertible to string. They are accepted without an explicit cast because fputcsv() and SplFileObject::fputcsv() accept them today, and this extension is meant to be the migration target for the latter. Requiring (string)
there seemed like friction without much benefit. If you see a strong reason to align fully, I’m open to changing it.

On your PS: I agree it’s worth doing, but I’ve kept it out of this RFC and listed it under Future Scope. Adding backed enum support to fputcsv() would not be a BC break, since enums currently throw there. Like the http_build_query() change in 8.4 (GH-15650, fixed via GH-15704 without an RFC), it could be
a small standalone PR for 8.7. Rejecting resources and arrays in the legacy functions, on the other hand, would be a BC break and would need a deprecation first.

Best regards,
Damian

On Tue, Nov 10, 2026 at 9:36 AM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Thu, Oct 29, 2026 at 4:30 PM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Fri, Oct 9, 2026 at 8:22 AM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

Hi Damien,
thanks for the proposal, indeed with the deprecation of SplFileObject CSV feature an object oriented alternative is welcomed having said that.I have a couple of remarks/suggestions

  • Following Tim’s thought, I wonder if a CSV top namespace is mandatory or if we should not just have a Serialization “namespace” name that can be improved when such classes and functions are defined.

  • RFC 4180-compatible parsing and serialization by default. As much as I am a proponent of backing RFC whenever they exist in this case it should be stressed out that RFC4180 is not an accepted RFC like for instance RFC3986 for URI specification as such it is totally possible to have a valid CSV which does not comply with the refer draft specification. I believe this should be noted and explained in the RFC to avoid pushing forward something which is not a real specification as anyone would expect even though it is widely accepted as the “default” implementation,

  • Hence why I believe that using terms like lax and strict is counter productive; probably other names “to be defined” should be used instead. Maybe adding an Enum With RFC4180 and something else (?) would be a better take. Which would reduce the number of function/methods introduced ?

  • Also while it is common to talk about CSV, this feature would be perhaps better called Character Separated Value than Comma Separated Value since the delimiter can be changed. And covers TSV and other exotic formats which separates values per single character.

The stream is owned by the object: like the stream of SplFileObject, it remains visible as a resource but fclose() refuses to close it, and it is closed when the object is destroyed (for an object alive until the end of the request, while destructors run, so a user wrapper’s stream_close() is still called).

Does it mean that the LazyLaxCollection will expose the stream metadata ? If I receive in my method/function a LazyLaxCollection is it possible for me to get access to the underlying resource metadata ? To know how it is open, its pathname , and so forth ? Can I easily detect if

Being able to configure the context or to apply stream filter is also something I find useful with the current set of csv function even with SplFileObject (even though it is tricky with that one) I would expect any API which aim at replacing the current CSV API to offer at most the same extensibility or to allow it in any other shape or form.

function collection_to_file(string $file, iterable $collection, string $delimiter = ',', string $enclosure = '"', string $eolSequence = "\r\n"): void {}

Why? can’t we have access to the written bytes as returned value. Otherwise it means we need to re-access the resource afterward if we want to get access to that value. For example if we want to generate the Content-Length header or something else ?

Overall, I like the direction of the RFC but I believe some major discussion points remain unsolved before going to a vote

Best regards,
Ignace

Hi Damien,

It just occurred to me that I forgot to mention one point: the RFC is missing a section defining the supported types, similar to the one included in the URI Query Parameters RFC: https://wiki.php.net/rfc/query_params#supported_types.

I believe such a section is important to avoid surprising behaviour when generating CSV data.

For instance, the current CSV implementation in PHP does not support converting objects of any kind. However, since the introduction of enums, both JSON serialization and http_build_query() support backed enums as values that can be converted. I would therefore expect backed enums to be supported by your proposal, or at the very least for this to be explicitly addressed in the RFC.

Conversely, resources are currently accepted during CSV conversion which we all agree is an unfamiliar behaviour. This RFC could therefore be a good opportunity to align CSV conversion with the new Query Params RFC (pending its acceptance) and the existing JSON conversion rules, establishing a common baseline for type conversion and serialization across PHP.

PS: I realise this is not really the focus of your RFC, but it also raises the question of whether support for backed enums should be added to PHP’s existing CSV functionality in PHP 8.7. After all, support for backed enums in http_build_query() was introduced in PHP 8.4, rather than being included when enums were first introduced.

Best regards,

Ignace

Hi Damien,

Thanks for adding the conversion rules. I have had a look at them, and there is one point I would like to raise.

I am not entirely convinced that allowing any object implementing Stringable to be implicitly cast to a string is the right approach.

In my opinion, this is somewhat of an anti-pattern because it relies on a generic string representation of an object rather than an explicit serialization contract. An object’s __toString() method is not necessarily intended to provide a suitable representation for CSV output.

I would suggest introducing a CSV-specific serialization interface instead, with a single dedicated method that explicitly defines how an object should be converted into a CSV field.

Something along the lines of PHP’s JsonSerializable interface:

interface CsvSerializable
{
    public function csvSerialize(): BackerEnum|string|int|float|bool|null;
}

Names can be changed/improved. The return type would be restricted to the types already supported by the CSV conversion rules. This would make the conversion explicit, predictable and consistent with the rest of the proposed serialization behaviour.

It would also give objects the opportunity to provide a CSV-specific representation without having to overload their general string representation for that purpose.

I believe this would be a cleaner and more extensible approach than relying on Stringable.

Best regards,
Ignace

Hi Ignace,

Thanks for the suggestion. I agree that a dedicated interface for converting objects into CSV fields could be useful.

I’d prefer to avoid the term “serialization”, as I’ve deliberately used “conversion” throughout the RFC. Something like Csv\FieldConvertible with a toCsvField() method would be more consistent with that terminology.

There is one thing I’d like to consider before introducing it, though.

The last item in the RFC’s Future Scope section already mentions the possibility of an object-oriented API. I think a dedicated conversion interface would fit quite naturally into such an API.

With the current function-based API, callers can already explicitly invoke their own conversion methods before passing values to the CSV functions:

Csv\array_to_row([
    $object->toCsvField(),
]);

This provides explicit control over the CSV representation without requiring a new interface in the initial API.

So the question, in my view, is whether we really need to introduce a dedicated interface now, or whether it would be better to revisit it alongside the potential object-oriented API, where its role and integration could be considered more broadly.

I’m not opposed to the interface itself. I’d just prefer to avoid expanding the initial scope unless there’s a compelling use case that the existing functions cannot reasonably accommodate.

Best regards,
Damian

On Tue, Nov 10, 2026 at 1:38 PM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Tue, Nov 10, 2026 at 12:07 PM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi Ignace,

Thank you, that’s a good catch. Writing the section showed that The RFC also contained an inconsistency between the documented behaviour and the implementation: it said unsupported fields throw a TypeError, but the implementation just did a plain string cast, exactly like fputcsv(). So arrays became “Array” with a warning, resources became “Resource id
#N” silently, and all enums threw a generic Error.

I’ve added a “Supported types” section to the RFC and updated the implementation to match. When writing, fields are converted as follows:

  • string: as is
  • null: empty field
  • bool: “1” / “0” (false used to be written as an empty field, which could not be told apart from null)
  • int: decimal representation
  • float: formatted with serialize_precision, like json_encode(). fputcsv() uses precision, so 0.1 + 0.2 was silently truncated to 0.3.
  • backed enum: its backing value
  • object convertible to string: the result of the string conversion (__toString(), or the internal cast of classes such as GMP)
  • pure enum, any other object, array, resource: TypeError

The error names the field and the row, e.g. Field “name” of element 3 of the collection must be of type null|bool|int|float|string|BackedEnum or an object convertible to string, resource given.

When reading, every field is returned as a string, with no type inference.

The one place where I deliberately diverge from the Query Params RFC is objects convertible to string. They are accepted without an explicit cast because fputcsv() and SplFileObject::fputcsv() accept them today, and this extension is meant to be the migration target for the latter. Requiring (string)
there seemed like friction without much benefit. If you see a strong reason to align fully, I’m open to changing it.

On your PS: I agree it’s worth doing, but I’ve kept it out of this RFC and listed it under Future Scope. Adding backed enum support to fputcsv() would not be a BC break, since enums currently throw there. Like the http_build_query() change in 8.4 (GH-15650, fixed via GH-15704 without an RFC), it could be
a small standalone PR for 8.7. Rejecting resources and arrays in the legacy functions, on the other hand, would be a BC break and would need a deprecation first.

Best regards,
Damian

On Tue, Nov 10, 2026 at 9:36 AM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Thu, Oct 29, 2026 at 4:30 PM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Fri, Oct 9, 2026 at 8:22 AM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

Hi Damien,
thanks for the proposal, indeed with the deprecation of SplFileObject CSV feature an object oriented alternative is welcomed having said that.I have a couple of remarks/suggestions

  • Following Tim’s thought, I wonder if a CSV top namespace is mandatory or if we should not just have a Serialization “namespace” name that can be improved when such classes and functions are defined.

  • RFC 4180-compatible parsing and serialization by default. As much as I am a proponent of backing RFC whenever they exist in this case it should be stressed out that RFC4180 is not an accepted RFC like for instance RFC3986 for URI specification as such it is totally possible to have a valid CSV which does not comply with the refer draft specification. I believe this should be noted and explained in the RFC to avoid pushing forward something which is not a real specification as anyone would expect even though it is widely accepted as the “default” implementation,

  • Hence why I believe that using terms like lax and strict is counter productive; probably other names “to be defined” should be used instead. Maybe adding an Enum With RFC4180 and something else (?) would be a better take. Which would reduce the number of function/methods introduced ?

  • Also while it is common to talk about CSV, this feature would be perhaps better called Character Separated Value than Comma Separated Value since the delimiter can be changed. And covers TSV and other exotic formats which separates values per single character.

The stream is owned by the object: like the stream of SplFileObject, it remains visible as a resource but fclose() refuses to close it, and it is closed when the object is destroyed (for an object alive until the end of the request, while destructors run, so a user wrapper’s stream_close() is still called).

Does it mean that the LazyLaxCollection will expose the stream metadata ? If I receive in my method/function a LazyLaxCollection is it possible for me to get access to the underlying resource metadata ? To know how it is open, its pathname , and so forth ? Can I easily detect if

Being able to configure the context or to apply stream filter is also something I find useful with the current set of csv function even with SplFileObject (even though it is tricky with that one) I would expect any API which aim at replacing the current CSV API to offer at most the same extensibility or to allow it in any other shape or form.

function collection_to_file(string $file, iterable $collection, string $delimiter = ',', string $enclosure = '"', string $eolSequence = "\r\n"): void {}

Why? can’t we have access to the written bytes as returned value. Otherwise it means we need to re-access the resource afterward if we want to get access to that value. For example if we want to generate the Content-Length header or something else ?

Overall, I like the direction of the RFC but I believe some major discussion points remain unsolved before going to a vote

Best regards,
Ignace

Hi Damien,

It just occurred to me that I forgot to mention one point: the RFC is missing a section defining the supported types, similar to the one included in the URI Query Parameters RFC: https://wiki.php.net/rfc/query_params#supported_types.

I believe such a section is important to avoid surprising behaviour when generating CSV data.

For instance, the current CSV implementation in PHP does not support converting objects of any kind. However, since the introduction of enums, both JSON serialization and http_build_query() support backed enums as values that can be converted. I would therefore expect backed enums to be supported by your proposal, or at the very least for this to be explicitly addressed in the RFC.

Conversely, resources are currently accepted during CSV conversion which we all agree is an unfamiliar behaviour. This RFC could therefore be a good opportunity to align CSV conversion with the new Query Params RFC (pending its acceptance) and the existing JSON conversion rules, establishing a common baseline for type conversion and serialization across PHP.

PS: I realise this is not really the focus of your RFC, but it also raises the question of whether support for backed enums should be added to PHP’s existing CSV functionality in PHP 8.7. After all, support for backed enums in http_build_query() was introduced in PHP 8.4, rather than being included when enums were first introduced.

Best regards,

Ignace

Hi Damien,

Thanks for adding the conversion rules. I have had a look at them, and there is one point I would like to raise.

I am not entirely convinced that allowing any object implementing Stringable to be implicitly cast to a string is the right approach.

In my opinion, this is somewhat of an anti-pattern because it relies on a generic string representation of an object rather than an explicit serialization contract. An object’s __toString() method is not necessarily intended to provide a suitable representation for CSV output.

I would suggest introducing a CSV-specific serialization interface instead, with a single dedicated method that explicitly defines how an object should be converted into a CSV field.

Something along the lines of PHP’s JsonSerializable interface:

interface CsvSerializable
{
    public function csvSerialize(): BackerEnum|string|int|float|bool|null;
}

Names can be changed/improved. The return type would be restricted to the types already supported by the CSV conversion rules. This would make the conversion explicit, predictable and consistent with the rest of the proposed serialization behaviour.

It would also give objects the opportunity to provide a CSV-specific representation without having to overload their general string representation for that purpose.

I believe this would be a cleaner and more extensible approach than relying on Stringable.

Best regards,
Ignace

On Tue, Nov 10, 2026 at 2:45 PM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi Ignace,

Thanks for the suggestion. I agree that a dedicated interface for converting objects into CSV fields could be useful.

I’d prefer to avoid the term “serialization”, as I’ve deliberately used “conversion” throughout the RFC. Something like Csv\FieldConvertible with a toCsvField() method would be more consistent with that terminology.

There is one thing I’d like to consider before introducing it, though.

The last item in the RFC’s Future Scope section already mentions the possibility of an object-oriented API. I think a dedicated conversion interface would fit quite naturally into such an API.

With the current function-based API, callers can already explicitly invoke their own conversion methods before passing values to the CSV functions:

Csv\array_to_row([
    $object->toCsvField(),
]);

This provides explicit control over the CSV representation without requiring a new interface in the initial API.

So the question, in my view, is whether we really need to introduce a dedicated interface now, or whether it would be better to revisit it alongside the potential object-oriented API, where its role and integration could be considered more broadly.

I’m not opposed to the interface itself. I’d just prefer to avoid expanding the initial scope unless there’s a compelling use case that the existing functions cannot reasonably accommodate.

Best regards,
Damian

On Tue, Nov 10, 2026 at 1:38 PM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Tue, Nov 10, 2026 at 12:07 PM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi Ignace,

Thank you, that’s a good catch. Writing the section showed that The RFC also contained an inconsistency between the documented behaviour and the implementation: it said unsupported fields throw a TypeError, but the implementation just did a plain string cast, exactly like fputcsv(). So arrays became “Array” with a warning, resources became “Resource id
#N” silently, and all enums threw a generic Error.

I’ve added a “Supported types” section to the RFC and updated the implementation to match. When writing, fields are converted as follows:

  • string: as is
  • null: empty field
  • bool: “1” / “0” (false used to be written as an empty field, which could not be told apart from null)
  • int: decimal representation
  • float: formatted with serialize_precision, like json_encode(). fputcsv() uses precision, so 0.1 + 0.2 was silently truncated to 0.3.
  • backed enum: its backing value
  • object convertible to string: the result of the string conversion (__toString(), or the internal cast of classes such as GMP)
  • pure enum, any other object, array, resource: TypeError

The error names the field and the row, e.g. Field “name” of element 3 of the collection must be of type null|bool|int|float|string|BackedEnum or an object convertible to string, resource given.

When reading, every field is returned as a string, with no type inference.

The one place where I deliberately diverge from the Query Params RFC is objects convertible to string. They are accepted without an explicit cast because fputcsv() and SplFileObject::fputcsv() accept them today, and this extension is meant to be the migration target for the latter. Requiring (string)
there seemed like friction without much benefit. If you see a strong reason to align fully, I’m open to changing it.

On your PS: I agree it’s worth doing, but I’ve kept it out of this RFC and listed it under Future Scope. Adding backed enum support to fputcsv() would not be a BC break, since enums currently throw there. Like the http_build_query() change in 8.4 (GH-15650, fixed via GH-15704 without an RFC), it could be
a small standalone PR for 8.7. Rejecting resources and arrays in the legacy functions, on the other hand, would be a BC break and would need a deprecation first.

Best regards,
Damian

On Tue, Nov 10, 2026 at 9:36 AM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Thu, Oct 29, 2026 at 4:30 PM ignace nyamagana butera <nyamsprod@gmail.com> wrote:

On Fri, Oct 9, 2026 at 8:22 AM Damian Jóźwiak <damian.jozwiak.lodz@gmail.com> wrote:

Hi internals,

I’d like to open the discussion on an RFC proposing a dedicated CSV extension (ext/csv) for PHP core.

RFC: https://wiki.php.net/rfc/csv_extension

Implementation: https://github.com/php/php-src/pull/24199

The proposal builds upon Gina Peter Banyard’s girgias/csv extension (BSD-3-Clause), with additional functionality for file and stream handling.

The motivation includes the deprecation of the SplFileObject CSV methods in PHP 8.6, which leaves certain use cases without a direct replacement.

The proposed extension provides:

  • Six functions and one class in the Csv\ namespace.

  • RFC 4180-compatible parsing and serialization by default.

  • Locale-independent processing without the proprietary escape mechanism.

  • Multibyte delimiters, enclosures, and EOL sequences.

  • Strict and lax collection parsing.

  • Lazy iteration over CSV files and streaming output.

The implementation includes PHPT tests covering parsing, serialization, stream handling, resource lifetime, and various edge cases.

The pull request’s CI checks are currently passing across the tested platforms, including debug, ZTS, and AddressSanitizer configurations.

The initial API is deliberately kept small. A more comprehensive object-oriented Reader/Writer API, including capability-oriented interfaces, is left for potential future discussion.

I’d particularly appreciate feedback on the public API design, the naming of LazyLaxCollection, and whether the extension should be always enabled or optional at build time.

For transparency, Gina has not reviewed or endorsed this RFC. Parts of the implementation were developed with LLM assistance; I have reviewed the code and take full responsibility for the contribution.

This is an invitation for discussion, not a call for votes.

Thanks in advance for your feedback.

Best regards,
Damian Jóźwiak

Hi Damien,
thanks for the proposal, indeed with the deprecation of SplFileObject CSV feature an object oriented alternative is welcomed having said that.I have a couple of remarks/suggestions

  • Following Tim’s thought, I wonder if a CSV top namespace is mandatory or if we should not just have a Serialization “namespace” name that can be improved when such classes and functions are defined.

  • RFC 4180-compatible parsing and serialization by default. As much as I am a proponent of backing RFC whenever they exist in this case it should be stressed out that RFC4180 is not an accepted RFC like for instance RFC3986 for URI specification as such it is totally possible to have a valid CSV which does not comply with the refer draft specification. I believe this should be noted and explained in the RFC to avoid pushing forward something which is not a real specification as anyone would expect even though it is widely accepted as the “default” implementation,

  • Hence why I believe that using terms like lax and strict is counter productive; probably other names “to be defined” should be used instead. Maybe adding an Enum With RFC4180 and something else (?) would be a better take. Which would reduce the number of function/methods introduced ?

  • Also while it is common to talk about CSV, this feature would be perhaps better called Character Separated Value than Comma Separated Value since the delimiter can be changed. And covers TSV and other exotic formats which separates values per single character.

The stream is owned by the object: like the stream of SplFileObject, it remains visible as a resource but fclose() refuses to close it, and it is closed when the object is destroyed (for an object alive until the end of the request, while destructors run, so a user wrapper’s stream_close() is still called).

Does it mean that the LazyLaxCollection will expose the stream metadata ? If I receive in my method/function a LazyLaxCollection is it possible for me to get access to the underlying resource metadata ? To know how it is open, its pathname , and so forth ? Can I easily detect if

Being able to configure the context or to apply stream filter is also something I find useful with the current set of csv function even with SplFileObject (even though it is tricky with that one) I would expect any API which aim at replacing the current CSV API to offer at most the same extensibility or to allow it in any other shape or form.

function collection_to_file(string $file, iterable $collection, string $delimiter = ',', string $enclosure = '"', string $eolSequence = "\r\n"): void {}

Why? can’t we have access to the written bytes as returned value. Otherwise it means we need to re-access the resource afterward if we want to get access to that value. For example if we want to generate the Content-Length header or something else ?

Overall, I like the direction of the RFC but I believe some major discussion points remain unsolved before going to a vote

Best regards,
Ignace

Hi Damien,

It just occurred to me that I forgot to mention one point: the RFC is missing a section defining the supported types, similar to the one included in the URI Query Parameters RFC: https://wiki.php.net/rfc/query_params#supported_types.

I believe such a section is important to avoid surprising behaviour when generating CSV data.

For instance, the current CSV implementation in PHP does not support converting objects of any kind. However, since the introduction of enums, both JSON serialization and http_build_query() support backed enums as values that can be converted. I would therefore expect backed enums to be supported by your proposal, or at the very least for this to be explicitly addressed in the RFC.

Conversely, resources are currently accepted during CSV conversion which we all agree is an unfamiliar behaviour. This RFC could therefore be a good opportunity to align CSV conversion with the new Query Params RFC (pending its acceptance) and the existing JSON conversion rules, establishing a common baseline for type conversion and serialization across PHP.

PS: I realise this is not really the focus of your RFC, but it also raises the question of whether support for backed enums should be added to PHP’s existing CSV functionality in PHP 8.7. After all, support for backed enums in http_build_query() was introduced in PHP 8.4, rather than being included when enums were first introduced.

Best regards,

Ignace

Hi Damien,

Thanks for adding the conversion rules. I have had a look at them, and there is one point I would like to raise.

I am not entirely convinced that allowing any object implementing Stringable to be implicitly cast to a string is the right approach.

In my opinion, this is somewhat of an anti-pattern because it relies on a generic string representation of an object rather than an explicit serialization contract. An object’s __toString() method is not necessarily intended to provide a suitable representation for CSV output.

I would suggest introducing a CSV-specific serialization interface instead, with a single dedicated method that explicitly defines how an object should be converted into a CSV field.

Something along the lines of PHP’s JsonSerializable interface:

interface CsvSerializable
{
    public function csvSerialize(): BackerEnum|string|int|float|bool|null;
}

Names can be changed/improved. The return type would be restricted to the types already supported by the CSV conversion rules. This would make the conversion explicit, predictable and consistent with the rest of the proposed serialization behaviour.

It would also give objects the opportunity to provide a CSV-specific representation without having to overload their general string representation for that purpose.

I believe this would be a cleaner and more extensible approach than relying on Stringable.

Best regards,
Ignace

Hi Damien,

The interface could be introduced later on, but removing __toString automatic conversion should be done now. so It may look like a BC break or a regression vs the current conversion rules but IMHO it would be beneficial in the long run. I would put the change in the same category as removing resource to string conversion as you did.

Best,
Ignace

Damian, Please respect the mailing list rules [1] and always reply with a bottom-post. This conversation as it is currently, is impossible to follow with Ignace (correctly) bottom posting and you consistently incorrectly top-posting. Smile, Juliette 1:

···

On 10-11-2026 14:44, Damian Jóźwiak wrote:

Hi Ignace,

Thanks for the suggestion. I agree that a dedicated interface for converting objects into CSV fields could be useful.

I’d prefer to avoid the term “serialization”, as I’ve deliberately used “conversion” throughout the RFC. Something like Csv\FieldConvertible with a toCsvField() method would be more consistent with that terminology.

There is one thing I’d like to consider before introducing it, though.

The last item in the RFC’s Future Scope section already mentions the possibility of an object-oriented API. I think a dedicated conversion interface would fit quite naturally into such an API.

With the current function-based API, callers can already explicitly invoke their own conversion methods before passing values to the CSV functions:

Csv\array_to_row([
    $object->toCsvField(),
]);

This provides explicit control over the CSV representation without requiring a new interface in the initial API.

So the question, in my view, is whether we really need to introduce a dedicated interface now, or whether it would be better to revisit it alongside the potential object-oriented API, where its role and integration could be considered more broadly.

I’m not opposed to the interface itself. I’d just prefer to avoid expanding the initial scope unless there’s a compelling use case that the existing functions cannot reasonably accommodate.

Best regards,
Damian

https://github.com/php/php-src/blob/master/docs/mailinglist-rules.md

On Tue, Nov 10, 2026 at 5:31 PM Juliette Reinders Folmer <php-internals_nospam@adviesenzo.nl> wrote:

On 10-11-2026 14:44, Damian Jóźwiak wrote:

Hi Ignace,

Thanks for the suggestion. I agree that a dedicated interface for converting objects into CSV fields could be useful.

I’d prefer to avoid the term “serialization”, as I’ve deliberately used “conversion” throughout the RFC. Something like Csv\FieldConvertible with a toCsvField() method would be more consistent with that terminology.

There is one thing I’d like to consider before introducing it, though.

The last item in the RFC’s Future Scope section already mentions the possibility of an object-oriented API. I think a dedicated conversion interface would fit quite naturally into such an API.

With the current function-based API, callers can already explicitly invoke their own conversion methods before passing values to the CSV functions:

Csv\array_to_row([
    $object->toCsvField(),
]);

This provides explicit control over the CSV representation without requiring a new interface in the initial API.

So the question, in my view, is whether we really need to introduce a dedicated interface now, or whether it would be better to revisit it alongside the potential object-oriented API, where its role and integration could be considered more broadly.

I’m not opposed to the interface itself. I’d just prefer to avoid expanding the initial scope unless there’s a compelling use case that the existing functions cannot reasonably accommodate.

Best regards,
Damian

Damian,

Please respect the mailing list rules [1] and always reply with a bottom-post. This conversation as it is currently, is impossible to follow with Ignace (correctly) bottom posting and you consistently incorrectly top-posting.

Smile,
Juliette

1: https://github.com/php/php-src/blob/master/docs/mailinglist-rules.md

Sorry about that, Juliette. I’ll make sure to bottom-post from now on.

On Tue, Nov 10, 2026 ignace nyamagana butera <nyamsprod@gmail.com> wrote:

The interface could be introduced later on, but removing __toString automatic conversion should be done now. so It may look like a BC break or a regression vs the current conversion rules but IMHO it would be beneficial in the long run. I would put the change in the same category as removing resource to string conversion as you did.

Hi Ignace,

I agree with your reasoning. I’ve updated the implementation to reject implicit __toString() conversions and published RFC version 1.4 to reflect this.

I’ve also added the dedicated conversion interface to Future Scope. I think it would fit naturally alongside the potential object-oriented API, without expanding the scope of this RFC.

Thanks again for the constructive feedback!

Best regards,

Damian

Hi Damian,

Thanks for working on this, and for taking in so much feedback already. The RFC 4180 default, locale independence and dropping the escape character are real improvements over the current functions.

I'd like to suggest a direction for the API, mainly about how options are passed. Every function currently takes $delimiter, $enclosure and $eolSequence, so callers repeat the same dialect on every call, and every future option has to be added to every signature. A small readonly value object for the format, with the RFC's current defaults, would avoid that, and an enum would make the quoting mode explicit:

    namespace Csv;

    enum Quoting { case Minimal; case All; case NonNumeric; }

    final readonly class Format {
        public function __construct(
            public string $delimiter = ',',
            public string $enclosure = '"',
            public string $eolSequence = "\r\n",
            public Quoting $quoting = Quoting::Minimal,
        ) {}
    }

A format object also allows new format options without changing the encoder and decoder APIs. For example, a configurable null representation to distinguish null from empty strings during round trips, or stripping a UTF-8 BOM when reading (as Excel commonly writes one).

The format could then be used by two small classes that do only the encoding and decoding:

    final class Encoder {
        public function __construct(Format $format = new Format()) {}
        public function encode(array $row): string {}
    }

    final class Decoder {
        public function __construct(Format $format = new Format()) {}
        public function decode(string $chunk): array {} // rows completed by this chunk
        public function finish(): array {} // end of input: last row, validation
    }

The decoder accepts input in arbitrary chunks, so it works with any source (files, sockets, HTTP bodies, decompression) without needing a separate function per source.

I'd deliberately keep stream and generator handling out of these classes. "Read a stream until EOF and decode it" and "encode everything a generator yields to a stream" are general patterns. A JSON Lines encoder and decoder would need exactly the same, and so would other formats later. If each format builds its own, we end up with a different streaming API per format. With minimal codecs, a later RFC could define a common interface for streaming any encoder or decoder, and CSV would get it for free.

Ignace's suggestion of an enum instead of the _lax suffix could fit here as a validation mode on the decoder.

I'm happy to help review or test the implementation if that's useful.

Frode