Hello,
I need to read csv file and analyze it to see if it contains error, and if errors occur then display error(s), and if not, then insert the values to the db.
The sample csv looks like
id,first_name,last_name,email
"12345","Jane","test@test.com" // incorrect row
"99999","John","Smith","test@test.com" // correct row
"232323",Sarah,"Smith","test@test.com" // incorrect row
I just put the comment beside each row for you guys understanding.
As you see, each row should contain 4 columns, each separated with comma(,), enclosed with “”
First row is not correct because it only has 3 columns, and in this case, it should display error like this
Line 2 "12345","Jane","test@test.com" Only 3 fields were found
and last row is not correct because Sarah is not enclosed with “” , and in this case, it should display error like this
Line 4 "232323",Sarah,"Smith","test@test.com" Firstname is not enclosed.
What I tried to do is
$handle = fopen($importFile, "r");
while (($line = fgetcsv($handle, 1000, ",",'"')) !== FALSE)
{
$num = count($line);
if ($num != 4)
{
do something;
}
:
:
}
Q1: How can I display the error causing line as it is (like
"12345","Jane","test@test.com"
) from csv file in the middle as I read it with fgetcsv?
I tried
for ($c=0; $c < $num; $c++)
{
echo $line[$c] . " ";
}
in the do something; place, but it prints
12345 Jane test@test.com
- no comma, no “”
Q2: my fgetcsv - fgetcsv($handle, 1000, “,”,‘"’) - does not catch the error for line 4, even though Sarah is not enclosed with “” , it considers the row not error and proceed as normal.
Why is it? I need to force the each value in csv to have enclosure “”
Thanks for your help in advance.