PHP-更新CSV文件中的特定行 [英] PHP - Update specific row in CSV file

查看:81
本文介绍了PHP-更新CSV文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种有效的方法来更新/删除CSV文件中的特定行?其他所有方法都包括读取整个文件的内容,创建临时文件,然后用它替换旧文件,等等. 但可以说,我有10000条记录的大型CSV,因此这种解决方案会占用大量资源. 假设我无法使用数据库,因此写入文件是存储数据的唯一方法. 因此,问题是,最有效的方法是什么? 预先谢谢你!

Is there an effective way to update/delete specific row in CSV file? Every other method included reading contents of entire file, creating temporary file and then replacing old file with it, etc... But let's say, I have big CSV with 10000 records, so this kind of solution would be rather resource-heavy. Let's say, I am unable to use database, so writing to file is the only way of storing data. So, the question is, what would be the most effective way to do it? Thank you in advance!

推荐答案

请考虑将csv逐行读取到多维数组中,并在某一行进行更改.然后,将阵列数据导出到csv.下面的示例假设以6列逗号分隔的csv文件(0-5)修改了第100行.

Consider reading the csv line by line into a multi-dimensional array, and at a certain row make your changes. Then, export array data out to csv. Below example modifies the 100th row assuming a 6-column comma delimited csv file (0-5).

现在,如果要删除该行,请通过有条件地跳到使用continue的下一个循环迭代,将其从$newdata数组中排除.另外,如果要更新,只需将当前内部数组$newdata[$i]设置为新值即可:

Now, if you want to delete the row, then exclude it from $newdata array by conditionally skipping to next loop iteration with continue. Alternatively, if you want to update, simple set current inner array $newdata[$i] to new values:

$i = 0;
$newdata = [];
$handle = fopen("OldFile.csv", "r");

// READ CSV
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {      

    // UPDATE 100TH ROW DATA (TO EXCLUDE, KEEP ONLY $i++ AND continue)
    if ($i == 99) {
        $newdata[$i][] = somenewvalue;          
        $newdata[$i][] = somenewvalue;   
        $newdata[$i][] = somenewvalue;  
        $newdata[$i][] = somenewvalue;
        $newdata[$i][] = somenewvalue;
        $newdata[$i][] = somenewvalue;
        $i++;
        continue;
    }  
    $newdata[$i][] = $data[0];          
    $newdata[$i][] = $data[1];    
    $newdata[$i][] = $data[2];      
    $newdata[$i][] = $data[3];    
    $newdata[$i][] = $data[4];    
    $newdata[$i][] = $data[5];
    $i++;    
}

// EXPORT CSV
$fp = fopen('NewFile.csv', 'w');    
foreach ($newdata as $rows) {
    fputcsv($fp, $rows);
}    
fclose($fp);

这篇关于PHP-更新CSV文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆