I had a csv file whose fields included data with line endings (CRLF created by hitting the carriage returns in html textarea). Of course, the LF in these fields was escaped by MySQL during the creation of the csv. Problem is I could NOT get fgetcsv to work correctly here, since each and every LF was regarded as the end of a line of the csv file, even when it was escaped!
Since what I wanted was to get THE FIRST LINE of the csv file, then count the number of fields by exploding on all unescaped commas, I had to resort to this:
<?php
/*
First five lines of csv: the 4th row has a line-break within a data field. The LFs represent line-feeds or \n
1,okonkwo joseph,nil,2010-01-12 17:41:40LF
2,okafor john,cq and sulphonamides,2010-01-12 17:58:03LF
3,okoye andrew,lives with hubby in abuja,2011-03-30 13:39:19LF
4,okeke peter,In 2001\, had appendicectomy in AbaCR
\LF
In 2004\, had ELCS at a private hoapital in Lagos,2011-03-30 13:39:19LF
5,adewale chris,cq and sulphonamides,2010-01-12 17:58:03LF
*/
$fp = fopen('file.csv', 'r');
$i = 1;
$str='';
$srch='';
while (false !== ($char = fgetc($fp))) {
$str .= $char;//use this to collect the string for outputting
$srch .= $char;//use this to search for LF, possible preceded by \'
if(strlen($srch) > 2){
$srch = substr($srch, 1);//ie trim off the first char
}
if($i > 1 && $srch[1] == chr(10) && $srch[0] != '\\'){//chr(10) is LF, ie \n
break;//if you get to the \n NOT preceded by \, that's the real line-ending, stop collecting the string;
}
$i++;
}
echo $str;//should contain the first line as string
?>
Perhaps there exists a more elegant solution to this issue, in which case I'd be glad to know!