如何使用 php 编辑(替换).csv文件中的一行


How to edit (replacing would be fine) a row in a .csv file using php?

所以我看了fputcsv,但它似乎替换了整个文件。有没有办法使用 PHP 替换或编辑 CSV 文件中的特定行?我不想上传(作为数组或其他一些数据结构)整个 CSV 编辑上传,然后替换或覆盖文件。我想就地编辑 CSV 文件。

例如,如果我有示例.csv它看起来像:

Name  Amount Price
Chair 500    20.00
Boat  20     20000.00

我想把椅子的数量换成100把。我如何通过编辑 CSV 文件来实现这一点?我可以在不上传整个文件的情况下做到这一点吗?我避免这样做,因为我认为这将是一个相当大的文件,并且可能会经常发生更改。

我还说上传这可能措辞不佳,因为这都是在服务器端而不是客户端完成的。

我的选择:

$f="file.csv";
$file=file_get_contents($f);
$file = str_replace("Chair 500", "Chair 100", $file);

file_put_contents($f, $file);

"危险,威尔·罗宾逊!" 不要尝试使用大于可用内存的文件

CSV,尽管它包含"格式化"数据,仍然只是一个平面文本文件。如果您要替换的文件与文件中的大小不同,例如您的10 -> 100 ,则必须重写文件以便为额外的字符腾出空间。你不能只是找到10在哪里并开始写作,因为这会开始覆盖 10 之后的任何内容,例如

foo;10;bar      <--original
foo;100bar      <--blind string replacement

现在它不再是 3 字段 CSV 记录。这是一个两场记录。同样,对于10 -> 2

foo;10;bar
foo;20;bar

10 -> 2 撕掉两个字符,用一个字符书写,并保留原来的第 2 个字符。现在,您已经将计数器增加了一倍,而不是减少了它。

基本上你必须这样做:

1) open new temp file
2) copy records from original CSV until you reach the record you want
3) read record into client-side
4) decode record into native data structure
5) modify data
6) write modified record out as csv to temp file
7) copy the remainder of the original file
8) delete original
9) rename temp -> original