0

Lets say we have a file opened with fopen. Is it possible to write to the same line we are reading from?

Basically im working with csv files, and i need to write values to the lines which dont have a second, or first value. (example1;example2)

Thanks.

Molnár Márk
  • 411
  • 1
  • 6
  • 14
  • 1
    possible duplicate of [How to write array values into a csv file in PHP?](http://stackoverflow.com/questions/4290693/how-to-write-array-values-into-a-csv-file-in-php) – eliasah Aug 16 '15 at 08:17
  • nope. im not working with arrays in any way. I have a csv file, some lines have a first value, some dont. if it doesnt have a first value, i need to write something into that line, as the first value. – Molnár Márk Aug 16 '15 at 08:22

1 Answers1

0

Example CSV:

Sally Whittaker,2018,McCarren House,312,3.75
Cushing House,148,3.52
Prescott House,17-D,3.20
Sandy Allen,2019,Oliver House,108,3.48

Second and third line - first two items missing. Code:

$file=file("csv.csv");

$str='';
foreach ($file as $line) {


    $liner=explode(',',$line);//use your own separator
    if(count($liner)<5) {

        array_unshift($liner, 'item1','item2');//put items at the start 
        $str.= implode(',', $liner);

    }
    else {
        $str.=implode(',', $liner);
    }
}

file_put_contents('csv.csv', $str);

Output CSV:

Sally Whittaker,2018,McCarren House,312,3.75
item1,item2,Cushing House,148,3.52
item1,item2,Prescott House,17-D,3.20
Sandy Allen,2019,Oliver House,108,3.48

EDIT: if csv (probably), have this structure:

Sally Whittaker,2018,McCarren House,312,3.75
,ddd,Cushing House,148,3.52
,xxxx,Prescott House,17-D,3.20
Sandy Allen,2019,Oliver House,108,3.48

code could be:

$file=file("csv.csv");

$str='';
foreach ($file as $line) {


    $liner=explode(',',$line);
    if($liner[0]=='') { //check if first item is empty!
        $liner[0]='item';

    }
    $str.=implode(',', $liner);
}

file_put_contents('csv.csv', $str);
sinisake
  • 11,240
  • 2
  • 19
  • 27
  • 1
    Good answer, however, @molnarpw keep in mind that doing this over a 500,000 lines of CSV file might terminate with out of memory. The file is first read in memory and lateron the modified data is written again. – mark Aug 16 '15 at 09:27
  • @mark, yes, you are right. Hope that .csv is not so huge. :) – sinisake Aug 16 '15 at 09:30