phpcsvfgetcsv

keep line breaks of csv datas


I'm using the kirby cms and some php to generate a text file from the datas of a csv file.

In the datas of my csv file, there are several paragraphs with line breaks into the text. I need to keep these line breaks into the text file generated.

Here is the code

<?php
  function csv(string $file, string $delimiter = ','): array{
    $lines = file($file);

    $lines[0] = str_replace("\xEF\xBB\xBF", '', $lines[0]);

    $csv = array_map(function($d) use($delimiter) {
     return str_getcsv($d, $delimiter);
    }, $lines);

    array_walk($csv, function(&$a) use ($csv) {
     $a = array_combine($csv[0], $a);
    });

    array_shift($csv);

    return $csv;
   }

I'm trying to figure out how to keep those line break into the text files. Thanks ! 🙏


Solution

  • Don't use file(), since it doesn't know that some of the newlines are interior to CSV records and shouldn't be used to split the data.

    Use a loop with fgetcsv(), it will parse the file correctly, assuming the fields with newlines are quoted properly.

    $fh = fopen($file);
    $header_line = fgets($fh);
    $header_line = str_replace("\xEF\xBB\xBF", '', $header_line);
    $keys = str_getcsv($header_line);
    $csv = [];
    
    while ($row = fgetcsv($fh, $delimiter)) {
        $csv[] = array_combine($keys, $row);
    }