Hướng dẫn php update csv file

Is there an effective way to update/delete specific row in CSV file? Every other method included reading contents of entire file, creating temporary file and then replacing old file with it, etc... But let's say, I have big CSV with 10000 records, so this kind of solution would be rather resource-heavy. Let's say, I am unable to use database, so writing to file is the only way of storing data. So, the question is, what would be the most effective way to do it? Thank you in advance!

asked Feb 16, 2016 at 18:22

6

You're going to have to read the entire file. Sorry, no way around that. A CSV is a single, flat, text file with randomly sized fields and rows.

You definitely shouldn't be working directly with a CSV for database operations. You ought to pull the data into a database to work with it, then output it back to CSV when you're done.

You don't mention why you can't use a database, so I'm going to guess it's a resource issue, and you also don't say why you don't want to rewrite the file, so I'm going to guess it's due to performance. You could cache a number of operations and perform them all at once, but you're not going to get away from rewriting all or at least some portion of the file.

answered Feb 16, 2016 at 18:31

0

Consider reading the csv line by line into a multi-dimensional array, and at a certain row make your changes. Then, export array data out to csv. Below example modifies the 100th row assuming a 6-column comma delimited csv file [0-5].

Now, if you want to delete the row, then exclude it from $newdata array by conditionally skipping to next loop iteration with continue. Alternatively, if you want to update, simple set current inner array $newdata[$i] to new values:

$i = 0;
$newdata = [];
$handle = fopen["OldFile.csv", "r"];

// READ CSV
while [[$data = fgetcsv[$handle, 1000, ","]] !== FALSE] {      

    // UPDATE 100TH ROW DATA [TO EXCLUDE, KEEP ONLY $i++ AND continue]
    if [$i == 99] {
        $newdata[$i][] = somenewvalue;          
        $newdata[$i][] = somenewvalue;   
        $newdata[$i][] = somenewvalue;  
        $newdata[$i][] = somenewvalue;
        $newdata[$i][] = somenewvalue;
        $newdata[$i][] = somenewvalue;
        $i++;
        continue;
    }  
    $newdata[$i][] = $data[0];          
    $newdata[$i][] = $data[1];    
    $newdata[$i][] = $data[2];      
    $newdata[$i][] = $data[3];    
    $newdata[$i][] = $data[4];    
    $newdata[$i][] = $data[5];
    $i++;    
}

// EXPORT CSV
$fp = fopen['NewFile.csv', 'w'];    
foreach [$newdata as $rows] {
    fputcsv[$fp, $rows];
}    
fclose[$fp];

answered Feb 16, 2016 at 19:41

ParfaitParfait

99.8k17 gold badges93 silver badges121 bronze badges

2

Break the CSV into multiple files all in one directory. That way you still have to rewrite files, but you don't have to rewrite nearly as much.

answered Feb 16, 2016 at 18:39

Parthian ShotParthian Shot

1,3401 gold badge13 silver badges23 bronze badges

Bit late but for people who may search same thing, you could put your csv into an sqlite what addionaly gives you the ability to search in the dataset. There is some sample code: Import CSV File into a SQLite Database via PHP

answered Aug 25, 2019 at 20:04

DwzaDwza

6,4274 gold badges38 silver badges69 bronze badges

Recommended Posts

    • Share

Hi,

I have a CSV file with the following columns; id, name, email

How can I loop through the file and just update the fields in the row that matches the particular id?

  • Quote

Link to commentShare on other sites

    • Share

Sorry if the answer isn't brilliant, it's my first post

Try using fopen to get the file contents and then use fgetcsv to parse the fields into an array, you can then loop through the array and change the rows for your particular id.

It may be really resource hungry but i'm an amateur myself so I'm not sure, this is just how I would go about it, the PHP manual is very handy.

  • Quote

Link to commentShare on other sites

  • Author

    • Share

Thanks 

I've got this so far but for some reason I am unable to open the file for reading and writing at the same time?

if[isset[$_POST]]{
$row = 1;
if [[$handle = fopen["customers.csv", "r+"]] !== FALSE] {
   while [[$data = fgetcsv[$handle, 1000, ","]] !== FALSE] {
       $num = count[$data];
       $row++;
       for [$c=0; $c < $num; $c++] {
        echo '$data[0] = ' . $data[0];
           if[$data[0] == $_POST['customerId']]{
            echo 'true';
            $data[1] = $_POST['name'];
            $data[2] = $_POST['email'];
           }
       
       }
       fputcsv[$handle, $data];
   }
   fclose[$handle];
}
}

  • Quote

Link to commentShare on other sites

    • Share

because the length of the data is likely different, you would need to write the output to a different/temporary file so that you don't corrupt the input file.

  • Quote

Link to commentShare on other sites

  • Author

    • Share

Thank you, I have updated it so the file is closed for reading and then opened for writing, but it's still not editing the file...

if[isset[$_POST]]{
	$row = 1;	
	if [[$handle = fopen["customers.csv", "r"]] !== FALSE] {
	    while [[$data = fgetcsv[$handle, 1000, ","]] !== FALSE] {
	        $num = count[$data];
	        $row++;
	        for [$c=0; $c < $num; $c++] {
	            // Customer ID exists so edit the record
	        	if[$data[0] == $_POST['customerId']]{
	            	$data[1] = $_POST['name'];
	            	$data[2] = $_POST['email'];	            
	            }
	       		
	        }	        
	    }
	    fclose[$handle];
	}
	if [[$handle = fopen["customers.csv", "w"]] !== FALSE] {
		fputcsv[$handle, $data];
	}
}

  • Quote

Link to commentShare on other sites

  • Author

    • Share

Thank you, I am using fputcsv[] but am having problems writing to the file, I am able to read from it... Could it be a permissions problem?

  • Quote

Link to commentShare on other sites

    • Share

the problem is your LOGIC.

you must open the input file for reading, open a separate new output file for writing. then as you loop through the lines from the input file, you replace/update the data if it matches the submitted post data, and you write each line [both the unchanged and the updated ones] to the output file.

  • Quote

Link to commentShare on other sites

    • Share

the problem is your LOGIC.

you must open the input file for reading, open a separate new output file for writing. then as you loop through the lines from the input file, you replace/update the data if it matches the submitted post data, and you write each line [both the unchanged and the updated ones] to the output file.

Then rename the two files, so the next time the process is run, you get the "new" file as input.

By the way: if there is any possibility that the page will be submitted from two different users, or even browser tabs, at the same time, you will experience data loss. This is one of the reasons that a database is recommended for data processing.

  • Quote

Link to commentShare on other sites

    • Share

starting with the logic in this thread - //forums.phpfreaks.com/topic/278189-csv-class-need-help-updating-a-csv-file/?hl=%2Btempnam you would end up with something that looks like -

$csvfile = 'customers.csv';

$tempfile = tempnam[".", "tmp"]; // produce a temporary file name, in the current directory

if[!$input = fopen[$csvfile,'r']]{
    die['could not open existing csv file'];
}
if[!$output = fopen[$tempfile,'w']]{
    die['could not open temporary output file'];
}

while[[$data = fgetcsv[$input]] !== FALSE]{
    if[$data[0] == $_POST['customerId']]{
        $data[1] = $_POST['name'];
        $data[2] = $_POST['email'];
    }
    fputcsv[$output,$data];
}

fclose[$input];
fclose[$output];

unlink[$csvfile];
rename[$tempfile,$csvfile];

echo 'done';

  • Quote

Link to commentShare on other sites

  • Author

    • Share

Thanks guys, unfortunately the above code doesn't work, which leads me to believe there is a permissions issue. I have even commented out the lines:

//unlink[$csvfile];

//rename[$tempfile,$csvfile];

and the temp file is not present in that directory...

  • Quote

Link to commentShare on other sites

    • Share

do you have php's error_reporting set to E_ALL and display_errors set to ON so that you would see all the php errors? if there's a permission problem, there would be a php error about it.

  • Quote

Link to commentShare on other sites

  • Author

    • Share

thanks! I have included error reporting and I am indeed having a permissions issue!

  • Quote

Link to commentShare on other sites

    • Share

Other way,

You should try this: //handsontable.com/

by copy and paste to table. i mean you open csv from excel and paste to handsontable form.

they use PDO to control Mysql but i don't know to convert to standard Php Mysql

Edited June 5, 2013 by phong_ux

  • Quote

Link to comment Share on other sites

    • Share

Perhaps...

if[isset[$_POST]]{
    $needle = $_POST['customerId'];
    $new_line = $needle . "," . $_POST['name'] . "," . $_POST['email'];
    $lines = file["customers.csv"];
    $c = count[$lines];
    $i = 0;
    while[$i

Chủ Đề