Search code examples
phpfgetcsv

PHP fgetcsv() where source file doesn't have an enclosure character?


I have an input CSV where the "columns" aren't enclosed in anything.

File contents ($input = fopen(filename);):


    1,2,3,4,5,6,7
    a,b,c,d,e,f,g
    9,8,7,6,5,4,3
    z,y,x,w,v,u,t

I'm having problems getting fgetcsv() to work because there isn't an enclosure around the values.



    while($row = fgetcsv($input)) {
      print_r($row);
    }

Results in:

1111

I've tried some basic things that I could think of off the top of my head:

fgetcsc($file, 0, ',', '\');

fgetcsc($file, 0, ',', '');

Any ideas for a work around? Manually editing my input file isn't really an option as it's several millions of lines.


Solution

  • It's not clear what your problem is. fgetcsv and str_getcsv also work with columns sans quotes:

    print_r(str_getcsv('1,2,3,4,5,6,7'));
    

    Returns:

    Array
    (
        [0] => 1
        [1] => 2
        [2] => 3
        [3] => 4
        [4] => 5
        [5] => 6
        [6] => 7
    )
    

    The quotes are optional and only intended for CSV which can have the column delimiter within the values:

     column1, "Column 2 with , comma inside", colum3