StevenOliver Posted April 15, 2020 Share Posted April 15, 2020 (edited) Sometimes my 3 column .csv file has commas within quotes: fruit , cherry , red vegetables , "celery, carrots" , green flowers , rose , fresh When I use this code, I need the data count to stay the same "3" for each row: while (($data = fgetcsv($handle,2000,',')) !== FALSE) { print count($data); // prints "3" ... then prints "4" .... then prints "3" } How do I get fgetcsv to see that "celery, carrots" is just one unit of data? Thank you. Edited April 15, 2020 by StevenOliver Quote Link to comment Share on other sites More sharing options...
gw1500se Posted April 15, 2020 Share Posted April 15, 2020 The enclosure parameter (4th argument) should default to double quotes. You might try specifying it anyway to see what happens. 1 Quote Link to comment Share on other sites More sharing options...
Barand Posted April 15, 2020 Share Posted April 15, 2020 steve.txt fruit , cherry , red vegetables , "celery, carrots" , green flowers , rose , fresh code $handle = fopen('steve.txt', 'r'); while ($line = fgetcsv($handle)) { echo '<pre>', print_r($line, 1), '</pre>'; } output Array ( [0] => fruit [1] => cherry [2] => red ) Array ( [0] => vegetables [1] => celery, carrots [2] => green ) Array ( [0] => flowers [1] => rose [2] => fresh ) Defaults give three per line for me. Quote Link to comment Share on other sites More sharing options...
gw1500se Posted April 15, 2020 Share Posted April 15, 2020 That is why I suggested specifying the enclosure parameter. I don't know how but perhaps the default is different on the OP's server. Quote Link to comment Share on other sites More sharing options...
StevenOliver Posted April 15, 2020 Author Share Posted April 15, 2020 Oh geeez......... the error was MY goofup! I was running a file_get_contents/file_put_contents script which sanitized/pre-processed the .csv file before running the fgetcsv script, and, let's just say I unwittingly "sanitized" a whole bunch of commas... Recently almost every line of code I type has a typo (too many hours staring at the computer), I think I need a vacation 😀  Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.