Do you want to be a good Web Developer?

Enter Your Email To Get Our Exclusive Tutorials
And Offer Right In Your Email

Join TalkersCode Community And Recieve Exclusive Tutorials
On Web Development Right Via Email.

Read And Write CSV File Using PHP

Thursday, Aug 25, 2016

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.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email