note 103276 added to function.fgetcsv
| From: | ifedinachukwu at yahoo dot com | Date: | Tue, 05 Apr 2011 12:43:51 +0000 |
| Subject: | note 103276 added to function.fgetcsv | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-178511@lists.php.net to get a copy of this message | ||
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!
----
Server IP: 69.147.83.197
Probable Submitter: 41.73.231.175
----
Manual Page -- http://www.php.net/manual/en/function.fgetcsv.php
Edit -- https://master.php.net/note/edit/103276
Del: integrated -- https://master.php.net/note/delete/103276/integrated
Del: useless -- https://master.php.net/note/delete/103276/useless
Del: bad code -- https://master.php.net/note/delete/103276/bad+code
Del: spam -- https://master.php.net/note/delete/103276/spam
Del: non-english -- https://master.php.net/note/delete/103276/non-english
Del: in docs -- https://master.php.net/note/delete/103276/in+docs
Del: other reasons-- https://master.php.net/note/delete/103276
Reject -- https://master.php.net/note/reject/103276
Search -- https://master.php.net/manage/user-notes.php