Hướng dẫn php parse csv line

I have been seeking the same thing without using some unsupported PHP class. Excel CSV doesn't always use the quote separators and escapes the quotes using "" because the algorithm was probably made back in the '80s or something. After looking at several .csv parsers in the comments section on PHP.NET, I have seen ones that even used callbacks or eval'd code and they either didn't work like needed or simply didn't work at all. So, I wrote my own routines for this and they work in the most basic PHP configuration. The array keys can either be numeric or named as the fields given in the header row. Hope this helps.

    function SW_ImplodeCSV[array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY']
    // SW_ImplodeCSV - returns 2D array as string of csv[MS Excel .CSV supported]
    // AUTHOR: 
    // RELEASED: 9/21/13 BETA
      { $r=1; $row=array[]; $fields=array[]; $csv="";
        $escapes=array['\r', '\n', '\t', '\\', '\"'];  //two byte escape codes
        $escapes2=array["\r", "\n", "\t", "\\", "\""]; //actual code

        if[$mode=='EXCEL']// escape code = ""
         { $delim=','; $enclos='"'; $rowbr="\r\n"; }
        else //mode=STANDARD all fields enclosed
           { $delim=','; $enclos='"'; $rowbr="\r\n"; }

          $csv=""; $i=-1; $i2=0; $imax=count[$rows];

          while[ $i < $imax ]
          {
            // get field names
            if[$i == -1]
             { $row=$rows[0];
               if[$fmt=='2D_FIELDNAME_ARRAY']
                { $i2=0; $i2max=count[$row];
                  while[ list[$k, $v] = each[$row] ]
                   { $fields[$i2]=$k;
                     $i2++;
                   }
                }
               else //if[$fmt='2D_NUMBERED_ARRAY']
                { $i2=0; $i2max=[count[$rows[0]]];
                  while[$i2

Chủ Đề