1

Let's see I have this in csv string (got it from cURL output):

"name";"gender";"address";"phone";\n
"John Doe"; "Male"; "Broke Street\n No. 69 South Pole";"911";\n

Something like that, I use explode to get to line by line, however there is a field that also use \n for new line thus mess up my array index. How can I workaround this, any idea?

1
  • Edited the actual csv content I got which has double quote on field. Commented Sep 3, 2012 at 3:29

3 Answers 3

2

That's a badly generated/corrupted .csv, in that case. If a field contains line breaks, then it should be surrounded by " so the csv parser can tell a line-break-to-start-new-record apart from line-break-inside-a-field-just-to-make-a-new-line apart.

Fix whatever's generating the csv, rather than trying to handle the garbage it's spitting out.

Sign up to request clarification or add additional context in comments.

3 Comments

I forgot to mention, the csv field is actually enveloped by double quotes, which I remove it with str_replace thus it leaves with that clean data atm. I will edit my post. So what csv parser should I use, the php str_getcsv?
that means you're corrupting the csv yourself. stop massaging the data before it's been parsed.
The reason because it works if the value has no containing new line or delimiter. So its as easy as using str_replace and explode to get the job done. Now if you are referring to str_getcsv($output,"\n",'"') or without enclosure param, the parser still fail to recognize the \n inside the field is not for new row line.
0

In your case, that's a malformed csv.

Actually you may use preg_match_all to parse that file, without caring whether it's a csv or not.

eg: preg_match('#([^;]+);([^;]+);([^;]+);([^;]+)\s?#', $csv_file_content, $matches);

Comments

0

Atm Im using str_replace to replace '";\n' to '";#n' or to something else you like and use explode to split #n delimiter to get every row.

I guess thats what works for me right now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.