I have a csv file with headers that sometimes have extra fields in a certain row. This is because there was a comma in the text field that was not escaped.
Is there a way to remove a row before converting into array?
Sample csv file:
CUST_NUMBER,PO_NUMBER,NAME,SERVICE,DATE,BOX_NUMBER,TRACK_NO,ORDER_NO,INV_NO,INV_AMOUNT
757626003,7383281,JACK SMITH,GND,20180306,1,1Z1370750453578430,2018168325,119348,70.70
757626003,7383282,GERALD SMITH, JR.,GND,20180306,1,1Z9R67670395033411,2018168326,119513,63.72
757626003,7383233,SCOTT R SMITH,GND,20180306,1,1Z1370750982624042,2018168329,119349,39.33
As you can see, row 3 has an extra field because Gilbert, JR. has a comma in the text field without being escaped which puts the JR. part of the name in the SERVICE column and knocks the GND field outside of the SERVICE column into a column without a heading.
I want to remove the entire row when the row has more fields than there are headers.
After the row is removed I will convert the remaining csv into an array with something like this.
<?
$csv = array_map("str_getcsv", file("FILE.CSV",FILE_SKIP_EMPTY_LINES));
$keys = array_shift($csv);
foreach ($csv as $i => $row) {
if(count($keys) == count($row)){
$csv[$i] = array_combine($keys, $row);
}
}
?>
unset($csv[$i]);when you find a bad row.$csv = array_values($csv);$csv[$i]worked. The rest of my code didn't work because I needed to add another if statement somewhere else to run only if$csv[$i]is not empty.