find and replace values in a flat-file using PHP

前端 未结 2 825
别跟我提以往
别跟我提以往 2021-01-14 06:27

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 valu

相关标签:
2条回答
  • 2021-01-14 07:27

    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

    0 讨论(0)
  • 2021-01-14 07:30

    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.

    0 讨论(0)
提交回复
热议问题