3

I have a .csv template I'd wish for people to fill up, save it and upload it.

The problem is this, assuming some users would insert hidden line breaks in a row, when using fgetcsv() it would output the row broken by the hidden line breaks.

How can I escape the line break or sanitize my data?

Possible solution:

assume first row is correct, $count = count the number of delimiters until line break, the rebuild the text into an array as long as $count;

but i think the're better options available.

LATER EDIT

Here's the input *IMPORTANT[ ! ] : the data inside the excel file is "fine", it isn't broken, it's a single row!!! saving it as a csv file and opening it in notepad shows the following

asd;"asd
asd
asd";asd;asd

Here's the code

$handle = fopen("file.csv","r");
$data = fgetcsv($handle,";");
while($data = fgetcsv($handle)) {
    $array = explode(";",$data[0]);
    print_r($array);
}
fclose($handle);

Here's the echoed data

Array ( [0] => asd [1] => "asd ) Array ( [0] => asd ) Array ( [0] => asd" [1] => asd [2] => asd [3] => ) 

Thanks

3
  • 1
    What do you mean with "hidden line"? Commented Oct 10, 2011 at 10:50
  • open an excel file and type in something, then press alt+enter then type in more stuff Commented Oct 10, 2011 at 10:57
  • 1
    @christi ...then save this file in csv format and read it with fgetcsv(). Surprised? Where are all your imaginary broken rows? Commented Oct 10, 2011 at 11:01

1 Answer 1

4

it is very easy to test your case and see that there are no broken rows, if fields being properly quoted.

So, a CSV line like this

1,"joe
""Big Coyote""
Hopkins",598600

will be read with not a single problem.

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

2 Comments

let's say i'd make a scrips that follows some predictable patterns, but i'm expecting that my users might submit wrong data, so i'd like to remove line breaks inside rows, i'll try to figure it out by my own, thanks for the lecture
and finally modified my script, and it finally works while($data = fgetcsv($handle,1000,';','"')) print_r($data); i might apologize for not making my problem clear enough but everything i read on php.net and I couldn't really figure it out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.