I am trying to add an ability to allow users of a wvb app to bulk upload data using a CSV file – everything works great except when the data includes a comma in the actual field itself.
There are lots of posts regarding this and I have read many ways of addressing it mainly by enclosing the comma in double quotes but I cannot figure out how to do this for my code.
Ultimately I cannot rely on users to do this for me at input time so I need to do it as part of the upload process before it hits the database – I tried using tab as an alternate separator but Excel seems to be very inconsistent in how it handles tab separation so I ruled that out.
(sanitiseData is a function I use throughout the site to clean all user input data)
$handle = fopen($file_path, 'r');
$row_count=0;
while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
if ($row_count==0) {
$row_count++;
} else {
$row_count++;
$works_id = sanitiseData($data[0]);
$title = sanitiseData($data[1]);
$first_name = sanitiseData($data[2]);
//Use data to insert into db
$sql = mysql_query("INSERT INTO csv_employee_personal (id,works_id,title,first_name) VALUES ('','$works_id','$title','$first_name')");
}
}
//delete csv file
unlink($file_path);
I’m presuming this is what your data looks like
“data”,”data2″,”data3,and some more”,”data4″
my regex is very bad , but I would think it would be your best solution.
in the mean time you can recursively go trough each character on a line and keep track of commas and field delimiters and when you realize that you are looking at a comma that was not followed by a closing ” then you can escape it.
If the example data I gave u matches your data, give me a few mins while I write a function for you to escape commas