CSV file import - problem with multiple line breaks in a field

Hi,

I have problems reading a CSV file with multiple line breaks in a field. Finally found the code, that can “break” the lines correctly. My problem now is how do I get all the lines from the CSV files in separate lines?

I did “echo” the lines to the screen - however this will be replaced with a code to import the line into a MySql database.

Somehow I need to do a loop through the CSV file, but I am not sure how to do that together with the code that help me “break” the lines in the right place…

[php]
$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
if($i > 1 && $srch[1] == “\r” && $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
[/php]

Thanks in advance!

Why are you reinventing the wheel? http://php.net/manual/fr/function.fgetcsv.php

while ($data = fgetcsv($handle) !== false) { print_r($data); }

Thanks for the answer,

Hoever it does not work for me… It reads the csv file, but as I wrote:

In some fields I have multiple line breaks. With your code, it will break the line when there are line breaks in fields inside the line…

The code I wrote will not break the line. The question is - how do I loop THAT code through the file?

Sponsor our Newsletter | Privacy Policy | Terms of Service