How to handle extra commas in csv file?

Discussion in 'PHP' started by greatlogix, Jan 10, 2011.

  1. #1
    I am creating csv using php like this
    Id,name,address,zip
    Some addresses have commas in them like Abc Street, #24H Comma in address is creating problem. Half of the address Abc street is in address column and remaining part of the address after comma #24H is in next column or box(zip). How i can fix that entire address appear in address column including comma.
     
    greatlogix, Jan 10, 2011 IP
  2. rainborick

    rainborick Well-Known Member

    Messages:
    424
    Likes Received:
    33
    Best Answers:
    0
    Trophy Points:
    120
    #2
    The solution is to either escape the commas or filter them out before inserting the data into your CSV file. If a comma occurs within the data fields of a CSV file, the only reasonable option is to verify each line of data before processing it and either report the error or ignore the data.
     
    rainborick, Jan 10, 2011 IP
  3. greatlogix

    greatlogix Active Member

    Messages:
    664
    Likes Received:
    13
    Best Answers:
    1
    Trophy Points:
    85
    #3
    how to escape commas? I tried this Abc Street\\, #24H but it also did not work.
     
    greatlogix, Jan 10, 2011 IP
  4. jkl6

    jkl6 Peon

    Messages:
    70
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You need to quote stuff that contains commas:
    id,name,"Abc Street, #24H",zip
     
    jkl6, Jan 10, 2011 IP
  5. seafrontsteve

    seafrontsteve Peon

    Messages:
    451
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Why not consider something other than commas as separators?
    Excel and oprn office work fine with other symbols such as tabs or semi-colons.
    I know that then becomes something other than a csv file, but does it matter?
    Guess it depends on whether you are using the output yourself or allowing downloads or auto-emailing it to others?
     
    seafrontsteve, Jan 10, 2011 IP
  6. atxsurf

    atxsurf Peon

    Messages:
    2,394
    Likes Received:
    21
    Best Answers:
    1
    Trophy Points:
    0
    #6
    Use fputcsv() to wright you file. It is standard function that will take care of all special characters - no need to reinvent the wheel
     
    atxsurf, Jan 10, 2011 IP