How to Update/Edit CSV File in PHP?

03-Apr-2023

.

Admin

How to Update/Edit CSV File in PHP?

Hi Dev,

This post will give you example of how to update/edit csv file in php?. This tutorial will give you simple example of how to csv file edit data in php. In this article, we will implement a php read and write csv file. you can understand a concept of php modify csv file.

Here, I will give the following example of Update/Edit CSV File in php program, we will use The fopen() this function opens a file or URL, the fgetcsv() function use to parses the line it reads for fields in CSV format and returns an array containing the fields read.

Example: update/edit csv file


I simply update/edit csv file:

sample.csv

index.php

<?php

header('Content-Type: text/csv');

header('Content-Disposition: attachment; filename="sample.csv"');

// csv file open

if (($open = fopen("sample.csv", "r")) !== FALSE)

{

// csv file get data and convert to array

while (($getdata = fgetcsv($open, 1000, ",")) !== FALSE)

{

$data[] = $getdata;

}

// file close

fclose($open);

}

// Append to new data in csv file

$data[] = ["id" => 4, "name" => "Mehul Bagda", "email" => "mehul@gmail.com"];

$data[] = ["id" => 5, "name" => "Piyush Kamani", "email" => "piyush@gmail.com"];

// csv File update

$file_Path = fopen('php://output', 'wb');

foreach ( $data as $data )

{

fputcsv($file_Path, $data);

}

// File close

fclose($file_Path);

?>

Output:

After the Add data in csv file Output

I hope it could help you...

#PHP