1

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 !

Hans
  • 27
  • 6
  • You should [enable warnings](https://stackoverflow.com/questions/12582409/php-on-openshift-how-to-enable-errors-and-warnings). then you will see a warning on the line `$a = array_combine($csv[0], $a);` with the text: "Warning: array_combine(): Both parameters should have an equal number of elements" – Luuk Oct 05 '20 at 16:23
  • Thanks for your reply. I did it and I have this message. When I delete the line breaks into the csv things are working fine and no error message. But I need to keep those line breaks. – Hans Oct 05 '20 at 16:26

1 Answers1

3

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);
}
Barmar
  • 741,623
  • 53
  • 500
  • 612