如何使用php在csv文件的特定位置插入值
是否可以使用 PHP 在 CSV 文件中的特定位置写入?
我不想在 CSV 文件末尾附加数据。但我想在 CSV 中已有值的行末尾添加数据。
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,由于文件系统的性质,不可能在文件中间插入新数据。
只能在末尾追加。
因此,唯一的解决方案是创建另一个文件,写入源文件的开始部分,附加一个新值,然后附加源文件的其余部分。最后将生成的文件重命名为原始名称。
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:
从技术上讲Col 。 Shrapnel的回答是绝对正确的。
您的问题是您不想处理所有这些文件操作只是为了更改某些数据。我同意你的看法。但你在错误的层面上寻找解决方案。把这个问题放在一个更高的层面上。创建一个代表 CSV 数据库中的实体的模型。修改模型的状态并调用其
save()
方法。该方法应该负责以 CSV 格式写入模型的状态。尽管如此,您仍然可以使用 CSV 库来为您抽象出低级操作。例如,parsecsv-for-php 允许您定位特定单元格:
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: