Jump to content

Recommended Posts

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 by StevenOliver
Link to comment
https://forums.phpfreaks.com/topic/310588-fgetcsv-sometimes-extra-comma/
Share on other sites

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.

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 😀

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.