Define Line Endings for fputcsv Function in PHP 8.1

Define Line Endings for fputcsv Function in PHP 8.1

PHP provides the fputcsv function which formats an array of fields as a CSV line and writes it to a file. Since PHP 8.1, this function accepts a new optional parameter which allows specifying a custom end of line character (default is \n).

For example, the following code writes data from array to CSV file by specifying custom line endings \r\n:

<?php

$data = [
    ['John', 25],
    ['Patrick', 20],
    ['Anna', 22],
];

$fp = fopen('test.csv', 'wb');
foreach ($data as $fields) {
    fputcsv($fp, $fields, eol: "\r\n");
}
fclose($fp);

You will get CSV file:

John,25
Patrick,20
Anna,22

Each line in CSV file end with \r\n.

Note: in versions prior to PHP 8.1, end of line character was hard coded to \n and cannot be changed.

Leave a Comment

Cancel reply

Your email address will not be published.