Want To Be A Blogger  →  Start A Blog  →  Increase Traffic  →  Make Money Online  →  Recommended Things

Read And Write CSV File Using PHP

Friday, Dec 15, 2017

Tags:- 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.In this tutorial we will show you how to read and write csv file using PHP.


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.

Subscribe Our Newsletter And Get Tutorials And Offers Via Email

About Me


Hello, My Name is Mudit Jain. I am a Web Developer, Professional Blogger and Digital Marketer from India. I am the founder of TalkersCode. I started this blog in february 2015 to help web developers & bloggers by providing easy and best tutorials, articles and offers for web developers and bloggers.