Explode CSV row,..But With An Exception..

Discussion in 'PHP' started by timallard, May 25, 2009.

  1. #1
    Hello,

    Im trying to explode a CSV row. There is 1 problem. The first Column isn't wrapped in quotes.

    I have this exploding content within the quotes:
    $new = explode('"',$new[0]);

    but how can i make an exception for the first column to be looked for without quotes,..then the next column has quotes? all separated by commas.

    e.x.

    Do all major league Empires work as a Group with the same schdule all year ? Or do they have each their own Schdule. ,"Alward","","email@comcast.net","03044","Fremont, NH","Sports","","","","","","","05/24/2009 6:48am"


    Thank You!
     
    timallard, May 25, 2009 IP
  2. felluahill

    felluahill Peon

    Messages:
    31
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Well if I'm not mistaken exploding by quotes would put the first part in $new[0]. Isn't that all you need?
     
    felluahill, May 25, 2009 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    You should be splitting or exploding using a comma as the delimiter. You can then strip the quotes if needed. If there is a field that may contain comma's, then you may need to use a preg_split and a regular expression to properly parse the csv string.
     
    jestep, May 25, 2009 IP
  4. tguillea

    tguillea Active Member

    Messages:
    229
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    90
    #4
    If you are exploding and there are multiple rows you should be first using a chr(10) to divide each row, then a comma, then use a simple if/else statement to see if it is the first row. Something along the lines of

    
    for ($x = 0; isset($row['value']); $x++){
        if ($x == 0) {
            //do whatever for the first row
            } else {
            //do whatever for the rest of the rows
            }
        }
    
    PHP:
    Hope that helps!
     
    tguillea, May 25, 2009 IP