user2921896
user2921896

Reputation:

PHP to remove 2nd line of CSV and rewrite CSV without that line

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

Upvotes: 1

Views: 1596

Answers (1)

ffflabs
ffflabs

Reputation: 17481

try prepending

array_shift($data);

right before

foreach ($data as $fields) {

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

Upvotes: 1

Related Questions