Search code examples
phparrayscsvfgetcsv

Read CSV, but create single array containing lines, not multidimensional array?


I have a CSV file and using fgetcsv I can happily generate each line as an array.

Pipes indicate structure and cell division, commas in the below are commas that are part of the input and need to be preserved.

abc,456|5hs6|dfdsf,56
abc,456|5hs6|dfdsf,56
abc,456|5hs6|dfdsf,56
abc,456|5hs6|dfdsf,56

Given that commas would be used in the data as shown, it would be better to separate using pipes.

Array(
[0] => abc,456|5hs6|dfdsf,56
[1] => abc,456|5hs6|dfdsf,56
[2] => abc,456|5hs6|dfdsf,56
[3] => abc,456|5hs6|dfdsf,56
)

Solution

  • If your CSV file is different from what you want to have in the array afterwards, e.g. the CSV is something like

    "1","2","3","4","5","6"
    "1","2","3","4","5","6"
    …
    

    or anything else that actually requires parsing it with fgetcsv then use

    $result = array();
    while (($line = fgetscsv($handler) !== false) {
      $result[] = implode(',', $line);
    }
    

    If your CSV file already contains what you want to have in the array afterwards, e.g.

    1,2,3,4,5,6
    1,2,3,4,5,6
    …
    

    then you dont need to parse it as CSV (which is slower), but can do

    $result = array();
    while (($line = fgets($handler) !== false) {
      $result[] = $line;
    }
    

    or just use $array = file('filename.csv')

    The difference is, that a) it is implicitly assumed, that the csv-source use , as separator, because we just take them as they are noted in the file, and b) it will not remove any enclosures (You may enclose a value in "to avoid a , within it is treated as a csv-delimiter), but that seems just useful here.