php8.5
Home/ Manual/ filesystem / functions/ fputcsv

fputcsv

PHP function Edit on GitHub ✎

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

Format line as CSV and write to file pointer

Description

fputcsv(resource $stream, array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\", string $eol = "\n"): int|false

fputcsv() formats a line (passed as a fields array) as CSV and writes it (terminated by a eol) to the specified stream.

Parameters

stream

All

fields

An array of strings.

eol

The optional eol parameter sets a custom End of Line sequence.

Escape-parameter

Note

If an enclosure character is contained in a field, it will be escaped by doubling it, unless it is immediately preceded by an escape.

Return Values

Returns the length of the written string Falseforfailure.

Changelog

VersionDescription
8.1.0The optional eol parameter has been added.
7.4.0The escape parameter now also accepts an empty string to disable the proprietary escape mechanism.

Examples

fputcsv() example

php
<?php

$list = [
    ['aaa', 'bbb', 'ccc', 'dddd'],
    ['123', '456', '789'],
    ['"aaa"', '"bbb"']
];

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields, ',', '"', '');
}

fclose($fp);
?>

The above example will write the following to file.csv:

output
aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""

See Also

  • fgetcsv()
  • str_getcsv()
  • SplFileObject::fgetcsv
  • SplFileObject::fputcsv
  • SplFileObject::setCsvControl
  • SplFileObject::getCsvControl

Source: reference/filesystem/functions/fputcsv.xml · from the official PHP manual (php/doc-en)