fgetcsv skip blank columns in csv file and gives Offset error

  fgetcsv, fputcsv, php

I have this script, it copies the data from file1 to newFile. And before copying it to new file, I fill out some empty columns using index (same for all rows) and it gives me an offset error.

For ex, my file1.csv looks like this

aa,bb,cc,,ee,,,
aa,bb,cc,,ee,,,
aa,bb,cc,,ee,,,
aa,bb,cc,,ee,,,

Output that I wish for is following

aa,bb,cc,abcd,ee,,,  
aa,bb,cc,abcd,ee,,, 
aa,bb,cc,abcd,ee,,,  
aa,bb,cc,abcd,ee,,,

Since 4th column is empty, (check file1.csv) fgetcsv only reads till cc, cuz it’s empty after cc. So ee got skipped. So output that I get with Offset error is(newFile), also remaining commas and delimeter commas are gone.

aa bb cc abcd
aa bb cc abcd
aa bb cc abcd
aa bb cc abcd

I want to create a newFile with all comma-separated values and with all remaining commas. Let me know if you could help me in either way.

Here is my script

//Open the old file for reading
$file1 = fopen("myfile2.csv", "r");
 
//Create a new file for writing
$newFile = fopen("$fname", "w+"); 

while (($row = fgetcsv($file1, 1000)) !== FALSE) {

$var = "abcd";

//insert at 3rd index
$row[3]=$var;

//write data into new file
fputcsv($newFile, array_values($row), ','); 

}
fclose($file);

Source: Ask PHP

LEAVE A COMMENT