find and replace values in a flat-file using PHP

独自空忆成欢 提交于 2019-12-01 09:07:59

A very easy way would it be to use str_replace() on the whole file:

// read the file
$file = file_get_contents('filename.csv');
// replace the data
$file = str_replace('folder|oldValue', 'folder|newValue', $file);
// write the file
file_put_contents('filename.csv', $file);

That should work as only one user the file at a time. But a database is always a better idea. If you need CSV, it's better to have an additional DB to CSV script than only a CSV file.

You can keep the list in memory using a PHP feature like APC and write it out every so often to disk. That way you're only reading it in when it doesn't exist in memory.

If you want to be performance orientated storing this info in a CSV is likely not the best to begin with. If you don't want to use a true RDMS (MySQL) then I'd suggest using SQLite. It provides all the features you're looking for (UPDATE) in this case and it acts exactly the same as a CSV in the sense that it's just a file on your harddrive and doesn't have concurrency.

If that's not an option the other way is to use shell level commands like sed & awk to do inline regular expression changes. Lastly, reading the whole file into a string, performing a nasty regex adjustment on it (s///) and then writing it out again would work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!