I'd think there was a question on this already, but I can't find one. Maybe the solution is too easy... Anyway, I have a flat-file and want to let the user change the values based on a name. I've already sorted out creating new name+value-pairs using the fopen('a')
mode, using jQuery to send the AJAX call with newValue
and newName
. But say the content looks like this:
host|http:www.stackoverflow.com
folder|/questions/
folder2|/users/
And now I want to change the folder
value. So I'll send in folder
as oldName
and /tags/
as newValue
. What's the best way to overwrite the value? The order in the list doesn't matter, and the name will always be on the left, followed by a |
(pipe), the value and then a new-line
.
My first thought was to read the list, store it in an array, search all the [0]
's for oldName
, then change the [1]
that belongs to it, and then write it back to a file. But I feel there is a better way around this? Any ideas? Maybe regex?
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
来源:https://stackoverflow.com/questions/2944080/find-and-replace-values-in-a-flat-file-using-php