Skip to content
PHP Logo

How can fputcsv be used to update specific rows in a CSV file while keeping other rows unchanged?

To update specific rows in a CSV file while keeping other rows unchanged, you can read the CSV file, update the specific rows as needed, and then write the updated data back to the CSV file using fputcsv. You can achieve this by reading each row of the CSV file, checking if it matches the rows you want to update, making the necessary changes, and then writing the updated data back to the CSV file.

php
<?php

// Open the CSV file for reading and writing
$csvFile = fopen('data.csv', 'r+');

// Array of rows to update
$rowsToUpdate = [2, 4, 6];

// Read the CSV file line by line
while (($data = fgetcsv($csvFile)) !== false) {
    // Check if the current row needs to be updated
    if (in_array($data[0], $rowsToUpdate)) {
        // Update the specific columns in the row
        $data[1] = 'Updated Value';
    }
    // Write the updated row back to the CSV file
    fputcsv($csvFile, $data);
}

// Close the CSV file
fclose($csvFile);

?>