Search code examples
phpcsvfputcsv

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


So I've looked at fputcsv but it seems to replace the whole file. Is there a way that a I can replace or edit a particular row in a CSV file using PHP? I do NOT want to upload (as an array or some other data structure) the entire CSV edit the upload and then replace or overwrite the file. I want to edit the CSV file in place.

For example if I had example.csv that looks like:

Name  Amount Price
Chair 500    20.00
Boat  20     20000.00

And I wanted to replace the amount of chair's to 100. How would I go about that by just editing the CSV file? Can I do it without uploading the entire file. I'm avoiding that because I'm thinking this is going to be a rather large file and changes may occur frequently.

Also I am saying upload this might be poorly phrased as this is all done on the server side not the client.


Solution

  • my option:

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

    “Danger, Will Robinson!” don't try with file larger than available memory