Some programmers think it is okay to use explode to split up a CSV file (usually a csv file is comma separated but sometimes it is tab separated or even some other separator is used). The reason it is a bad idea to use a simple explode is because your data can easily contain the separator in the content. This is very very common with comma's. Here is a quick example of data that excel would return when converting a sheet to CSV. id, name, address 1,james,100 smith street 2,billy,"200 smith street, apt 2" As you can see on the 3rd line (2nd line of data) excel was smart enough, as should any program that creates a csv file, to quote the column that has the separator that is being used. When doing an explode on the information above we are going to get 4 columns on the 3rd line instead of 3 columns and the content of those 4 columns will be column 1: 2 column 2: billy column 3: "200 smith street column 4: apt 2" Where if fgetcsv() was used, a function built into php, you would get the following columns column 1: 2 column 2: billy column 3: 200 smith street, apt2 So as you can see we get the data how we want it and it even removes the quotes that were not there originally. Happy Coding!
1 OLDER COMMENT
posted by Jaimie Sirovich on: Mar 27, 2006 06:50pm
Use this to create well-formed CSVs, and use an escape function that doubles up "'s. This is another common mistake people make. function escapeMS($string) { return str_replace('"', '""', $string); } function quotedImplode($glue, $array, $quote_char = "'", $escape_function = "addslashes") { foreach ($array as $i => $a) { $array[$i] = $quote_char . $escape_function($array[$i]) . $quote_char; } return implode($glue, $array); }
1 COMMENT