resonance
resonance

Reputation: 47

Dealing with line breaks in individual cells in a CSV file

I'm currently working on a webapplication that will take the data from a CSV file, and convert it into an array for easier access to specific data in the file. I do however have a problem. Currently my code looks something like this:

$data = file_get_contents('data.csv');
$array = str_getcsv($data,"\n");
$i = 0;

foreach($array as $row){
     $newArray[$i] = str_getcsv($row,";");
     $i++;
}

This works fine for the most part, but it messes up when there is a line break inside an individual value. I'm working with product descriptions so some of the companies put intentional line breaks in their descriptions. When I open the file in Excel I can see these linebreaks clearly, and my question is now, how do I deal with them? I've tried a lot of different approaches and read a lot online, but nothing seems to work for me.

I hope you can help me find a solution.

EDIT

Here is an example from the CSV file

5124;"Altid billig el og 5 stjerner på Trustpilot";"Altid billig el og 5 stjerner på Trustpilot.@ Vi har kun ét produkt og du skal ikke længere spekulere i om du nu har en billig elleverandør efter 6 måneder eller lign. Vi går efter at være blandt de billigste elleverandører, hvilket vi også beviser hvert år."

I don't know if it makes much sense, but this where the problem is. In this particular exampel there is a "forced" line break when I open it in excel, where i placed a bold "@". As far as I can see this should be valid?

Upvotes: 2

Views: 2030

Answers (1)

deceze
deceze

Reputation: 522005

str_getcsv expects one row of CSV formatted text, you cannot use it to parse an entire file. Let fgetcsv read and parse the file line by line:

$file = fopen('data.csv', 'r');
$data = [];

while ($row = fgetcsv($file)) {
     $data[] = $row;
}

fclose($file);

var_dump($data);

Upvotes: 2

Related Questions