logesh kumar
logesh kumar

Reputation: 88

Append data to middle line/row of a csv instead of the last line or row

I have a csv file with some records and each record has unique ID. I'm running a loop to find that unique ID and then append some more data to that record.

Is it possible to do this without a temporary file? Creating such file and moving all data in it takes more time...

My code is:

<?php 
$temp = fopen('tempwin.csv','w+');

if (($handle = fopen("win.csv", "r+")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;

        for ($c=0; $c < $num; $c++) {                        
            if($data[4] == trim($leadid)){
                $data[5] = trim($_POST['year']);
                $data[6] = trim($_POST['make']);
                $data[7] = trim($_POST['model']);
                $data[8] = trim($_POST['trade']);
            }
        }

        fputcsv($temp, $data);
    }

    fclose($handle);
    fclose($temp);
}

unlink('win.csv');
rename('tempwin.csv','win.csv');

Upvotes: 2

Views: 811

Answers (2)

Aftab Muni
Aftab Muni

Reputation: 171

You can use following, but you need to pass the row number i.e where you need to add row.

<?php
//A helping function to insert data at any position in array.
function array_insert($array, $pos, $val)
{
    $array2 = array_splice($array, $pos);
    $array[] = $val;
    $array = array_merge($array, $array2);

    return $array;
}

//What and where you want to insert
$DataToInsert = '11,Shamit,Male';
$PositionToInsert = 3;

//Full path & Name of the CSV File
$FileName = 'data.csv';

//Read the file and get is as a array of lines.
$arrLines = file($FileName);

//Insert data into this array.
$Result = array_insert($arrLines, $PositionToInsert, $DataToInsert);

//Convert result array to string.
$ResultStr = implode("\n", $Result);

//Write to the file.
file_put_contents($FileName, $ResultStr);
?>

Upvotes: 1

Danny Kopping
Danny Kopping

Reputation: 5200

Fetch the data out of the original file as an array or string, make your modifications and then simply overwrite the contents of the file with your modified data.

Upvotes: 0

Related Questions