1

Been hunting high and low for this one. I have a script that creates an array from the 2nd row/line of a CSV file, leaving the headers alone, then does it's thing. Great!

BUT when it's done I want to remove/delete that 2nd line from the CSV file so the next time my script runs it's using the next row coming up.

I've tried PHP code ideas like this with no luck so far.

$cnt = 0;
if (($handle = fopen("Alabama.csv", "r")) !== FALSE) {
while (($csvadata = fgetcsv($handle, 0, ",")) !== FALSE) {      
   $data[$cnt++] = $csvadata;
}
fclose($handle);
  unset($data[2]);
}
$fp = fopen('Alabama.csv', 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
 }
fclose($fp);

Here is a sample of the input file. I've included the header row and the first row of data. I need to remove the 1st line of data and keep the header intact. I've show here up to column E for example but the file actually goes to column T. Also each file will have AT MOST 4000 lines/rows.

                STATE        FDICCERT    ADDRESS               ASSETS     CITY                              
                Alabama         35         100 North Gay Street  768256   Auburn

1 Answer 1

1

try prepending

array_shift($data);

right before

foreach ($data as $fields) {

That way you will skip the first $data item when writing your file.

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

4 Comments

Actually it something - it deleted the row like I wanted it to, but it also deleted the header - is there way to do the shift without deleting the header? Or a way to replace the header after the shift?
Uh... can we see a sample of the input file? I neglected to ask in which row are you stripping out the headers and where do you need to store them, and what's in the additional row you need to delete.
I'm stripping out the second line only each run of my script and it's uses the headers to create an associative array, so I need the headers intact in line 1 at all times when running the script. So run script once
Run script once - use header and 2nd line for associative array. Run again after deleting the used 2nd line. So on the second running of the script we are actually using the header and the 3rd line from the original CSV file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.