Join TalkersCode Now !

Get Latest Tutorials And Links On Web Development
And Get Existing Offers Via Email

Read And Write CSV File Using PHP

Friday, Jan 27, 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.

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

Are You Starting A New Blog
Do You Want Best Web Hosting?

Try World's Best Web Hosting Provider BlueHost
At Just $3.95/mo

Hurry Up! Limited Time Offer

Yes, I Want To Check Out BlueHost

Check The World's Best SEO And All-In-One Marketing Toolkit
For Digital Marketing Professionals SEMRUSH

Check Out SEMRUSH