All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

Read And Write CSV File Using PHP

Last Updated : Jul 1, 2023

IN - PHP | Written & Updated By - Dikshita

In this tutorial we will show you how to read and write csv file using PHP, CSV (Comma Separated Value) file are those file in which the text is separated by comma these file are extremely easy to read and write and also to insert into database.

Read And Write CSV File Using PHP

To Read And Write CSV File It Takes Only One Step:-

  1. Make a PHP file to read and write csv file

Step 1. Make a PHP file to read and write csv file

We make a PHP file and save it with a name csv_file.php

<html>
<body>
<div id="wrapper">

<?php

// To Reac CSV File
$csvfile = 'sample_text.csv';
$file_handle = fopen($csvfile, 'r');
while(!feof($file_handle))
{
 echo fgetcsv($file_handle, 1024);
}
fclose($file_handle);


// To Write CSV File
$list = array
(
"Aman,18,20000",
"Rohit,20,24000"
);
$file = fopen("sample_text.csv","w");
foreach ($list as $line)
{
 fputcsv($file,explode(',',$line));
}
fclose($file);

?>

</div>
</body>
</html>

In this step we first create a 'sample_text.csv' file manually to show you how to read and write csv file.

To read csv file we use fopen function in read mode and use php fgetcsv function which is built to read csv files and then using while loop to display all the values.

Then to write values in csv file we create an array of values and again uses fopen function but this time in write mode because we have to write data in file then we use fputcsv function inside foreach loop to put data in csv file.

That's all, this is how to read and write csv file using PHP. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

I hope this tutorial on read and write csv file using PHP helps you and the steps and method mentioned above are easy to follow and implement.