Embedded comma causing problem with csv creation

Discussion in 'PHP' started by patter, May 5, 2010.

  1. #1
    I need to write data to a csv file. As long as the data doesn't contain commas, it works fine. But if it does, the format of the csv file is corrupted due to the extra commas. Here is some test code I wrote to show the problem.

    $csvdata = "col1,col2,col3" . "\n";
    $csvdata .= "bob" . " , " ;
    $csvdata .= "sally" . " , " ;
    $csvdata .= "tom, sue" . " , " ;
    $csvdata .= "\n";
    
    $fp = fopen( 'testfile.csv' , "w" );
    fwrite($fp,$csvdata); 
    fclose($fp);
    PHP:
    The result is:
    col1 col2 col3
    bob sally tom sue

    where sue is in the fourth column. Would someone please point out how to handle the extra commas?
     
    patter, May 5, 2010 IP
  2. dazst

    dazst Active Member

    Messages:
    115
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    78
    #2
    The problem is the parser that reads your csv file. You need to:
    1. Either modify the parser to ignore commas within the double-quotes.
    2. Or use a different field-separator, for example pipe | or single-quote ' or @

    I'm an expert programmer, feel free to hire me for any work.
    Here's some info: http://forums.digitalpoint.com/showthread.php?t=1791552
     
    dazst, May 5, 2010 IP
  3. kmap

    kmap Well-Known Member

    Messages:
    2,215
    Likes Received:
    29
    Best Answers:
    2
    Trophy Points:
    135
    #3
    use str_replace comma by zzzzzzzzzzzz

    then while displaying it again replace zzzzzzzzzzzz by comma

    Regards

    Alex
     
    kmap, May 5, 2010 IP
  4. patter

    patter Member

    Messages:
    32
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #4
    Thank you both for the responses. But the file is being read with excel by different users so creating a file that all of the users can only read if they alter their excel settings isn't a workable solution. There must be a way to create a file that doesn't depend upon the user having to adjust their settings. Does anyone have any other suggestions?
     
    patter, May 5, 2010 IP
  5. patter

    patter Member

    Messages:
    32
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    41
    #5
    The following works. I thought I would post it here in case someone else needs to know how to do it.

    $csvdata = array();
    $csvdata[] = array("col1","col2","col3"); 
    $csvdata[] = array("bob","sally","bob, sally");
    
    $fp = fopen( 'testfile.csv' , "w" );
    foreach ($csvdata as $record) { 
        fputcsv($fp, $record); 
    } 
    fclose($fp); 
    PHP:
     
    patter, May 5, 2010 IP