开发者

how to insert value in a particular location in csv file using php

开发者 https://www.devze.com 2023-01-11 10:19 出处:网络
Is it possible to write at a particular location in a CSV file using PHP? I don\'t want to append data at the end of the CSV file. But I want to add data at the end of a row already having values in

Is it possible to write at a particular location in a CSV file using PHP?

I don't want to append data at the end of the CSV file. But I want to add data at the end of a row already having values in the CSV.

thanks 开发者_高级运维in advance


No, it s not possible to insert new data in the middle of a file, due to filesystem nature.
Only append at the end is possible.

So, the only solution is to make another file, write a beginning part of source, append a new value, and then append the rest of the source file. And finally rename a resulting file to original name.


There you go. Complete working code:

<?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);
?>


Technically Col. Shrapnel's answer is absolutely right.

Your problem is that you don't want to deal with all these file operations just to change some data. I agree with you. But you're looking for the solution in a wrong level. Put this problem in a higher level. Create a model that represents an entity in your CSV database. Modify the model's state and call its save() method. The method should be responsible to write your model's state in CSV format.

Still, you can use a CSV library that abstracts low level operations for you. For instance, parsecsv-for-php allows you to target a specific cell:

$csv = new parseCSV();
$csv->sort_by = 'id';
$csv->parse('data.csv');
# "4" is the value of the "id" column of the CSV row
$csv->data[4]['firstname'] = 'John';
$csv->save();
0

精彩评论

暂无评论...
验证码 换一张
取 消