PHP offers a function called fputcsv which converts an array to a CSV line format, however it assumes you always want line endings as \n. There is often a situation, especially with Windows and Excel, where the default line ending of \n will cause the CSV file to not be opened correctly. Excel may run everything on one line, and other programs may completely bail. This function extends fputcsv to allow for an additional argument specifying a different line ending such as \r\n which is often required for Windows based programs.

/**
 * Extended fputcsv with ability to specify line ending
 *
 * This function extends the original PHP fputcsv with the ability to specify your line ending.
 *
 * @see https://www.php.net/manual/en/function.fputcsv.php
 *
 * @param resource $handle A valid file pointer opened by fopen or fsockopen
 * @param array $fields An array of strings
 * @param string $delimiter By default uses commas
 * @param string $enclosure By default uses double quotes
 * @param string $escapeChar By default uses \\
 * @param string $eol By default uses \n
 * @return int Returns the length of written string accounting for line ending change or false on failure
 */
function fputcsvEol($handle, $fields, $delimiter = ',', $enclosure = '"', $escapeChar = '\\', $eol = "\n"): int
{
    $return = fputcsv($handle, $fields, $delimiter, $enclosure, $escapeChar);
    if ($return !== false && "\n" != $eol && 0 === fseek($handle, -1, SEEK_CUR)) {
        $return += fwrite($handle, $eol) - 1;
    }

    return $return;
}

This code snippet was published on It was last edited on

0

0 Comments

  • Votes
  • Oldest
  • Latest