php8.5
Home/ Manual/ spl / splfileobject/ SplFileObject::fputcsv

SplFileObject::fputcsv

PHP function Edit on GitHub ✎

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

Write a field array as a CSV line

Description

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

Writes the fields array to the file as a CSV line.

Parameters

fields

An array of values.

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 stringFalseforfailure.

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

SplFileObject::fputcsv example

php
<?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$file = new SplFileObject('file.csv', 'w');

foreach ($list as $fields) {
    $file->fputcsv($fields);
}

?>

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

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

See Also

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