I’m using wp-table for a Wordpress project, and you can read in data from a csv file and it builds a table for you. At least, that’s the theory. In fact, it uses PHP’s built-in fgetcsv() function. Which blows.
fgetcsv() does a good job of parsing lines which are comma separated values, but it’s really profoundly retarded about understanding that the end of a line is the end of a record. If you read in 1000 bytes, you could have 10 records/line in there, but it mashes them all into one array.
So I wrote my own. It’s pretty basic, but it works.
function parse_csv_file($file, $columnheadings = false, $delimiter = ';', $enclosure = '"') { $row = 1; $rows = array(); $file_contents = file_get_contents($file); // determine the line break character sequence $line_break = chr(13) . chr(10); $pos = strpos($file_contents, $line_break); if ($pos === false) { // didn't find that $line_break = chr(10); $pos = strpos($file_contents, $line_break); if ($pos === false) { // not that either $line_break = chr(13); $pos = strpos($file_contents, $line_break); if ($pos === false) { // uh oh // Cannot determine line break character sequence. exit; } else { // Line breaks on 13 } } else { // Line breaks on 10 } } else { // Line breaks on 13.10 } $lines = split($line_break, file_get_contents($file)); foreach ($lines as $line_num => $line) { $line = trim($line); if ($line == '') continue; $l = array(); $enc = false; $v = ''; for ($i = 0; $i < strlen($line); $i++) { $char = substr($line, $i, 1); if ($char == $enclosure) { if ($enc) { $enc = false; } else { $enc = true; } } else if ($char == $delimiter) { if ($enc) { $v .= $char; } else { $l[] = $v; $v = ''; } } else { $v .= $char; } } // end foreach character in this line $rows[] = $l; } return $rows; }