Hi

I'm sure this is relatively simple but for some reason i'm struggling to understand how this function works. I have a csv made of lines like:

"john","smith","united kingdom","address line 1, address line 2","telephone"

fgetcsv($handle, 100000, ',', '"'))

is returning

Array ( [0] => "john" [1] => "smith" [2] => "united kingdom" [3] => "address line 1" [4] => "address line 2" [5] => "telephone" )

As you can see it splits the fourth value into two, yet i thought the fgetcsv enclosure value of '"' should keep these values as one?

Thanks

Ant

    Incidentally, if i change it to fgetcsv($handle, 100000, '","', '"') it will give me

    Array ( [0] => [1] => john [2] => , [3] => smith [4] => , [5] =>united kingdom [6] => , [7] => address kine 1, address line 2 [8] => , [9] => telephone [10] => )

    Which is close but now i have extra keys with just a comma in them. I'll also get a Notice:

    Notice: fgetcsv(): delimiter must be a single character

      Do you need that fourth parameter ?
      I just do this: fgetcsv($handle, 1000, ",")

        well i don't think you need either as they are the default values anyway. I've just put them in to show that i (think) i'm setting them correctly. Removing the fourth parameter makes no difference as it's the default.

          FWIW.. I've had no problems with text with commas, if it's wrapped in quotes

            Works fine for me as well with no extra parameters:

            $fp = fopen( "php://temp", 'w' );
            fputs( $fp, '"john","smith","united kingdom","address line 1, address line 2","telephone"' );
            rewind( $fp );
            print_r( fgetcsv( $fp ) );

            output:

            Array
            (
                [0] => john
                [1] => smith
                [2] => united kingdom
                [3] => address line 1, address line 2
                [4] => telephone
            )

              Are you sure the [font=monospace]"[/font] in the file really are [font=monospace]"[/font] and not, say, [font=monospace]“[/font]/[font=monospace]”[/font]?

                i gave up in the end and resorted to pipe delimited which worked fine. I think there was some issue with my csv file when it got uploaded, possibly an encoding issue. That can be the only explanation.

                  I've noticed some weird differences between MS Excel and other spreadsheet programs like OpenOffice and LibreOffice. I've also noticed that when i import certain data that certain values get preceded by an apostrophe or single quote '. And then there's the possibility of curly quotes getting put in when someone manually copies data and pastes it somewhere (AHEM, MS Word).

                  The pipe delimiter is a good solution unless your data contains pipes.

                  Could you perhaps post examples of the data file and code that were causing problems?

                    Write a Reply...