Home » PHP18 October 2010

PHP: Read Write CSV

In this article, I will be showing you how to read and write CSV file with PHP.

I have used PHP function fgetcsv to read CSV fields and fputcsv to write on CSV file.

fgetcsv — Gets line from file pointer and parse for CSV fields.
fgetcsv() parses the line it reads for fields in CSV format and returns an array containing the fields read.
This works on PHP 4 and PHP 5.

fputcsv — Format line as CSV and write to file pointer.
fputcsv() formats a line (passed as a fields array) as CSV and write it (terminated by a newline) to the specified file handle.
This works on PHP 5 or greater.

DOWNLOAD SOURCE CODE

Read CSV file

The following code reads data from a CSV file read.csv and displays in tabular form.

Write CSV file

The following code writes data to a CSV file file.csv. The data will be in the form of array. Each element will be the row of CSV file. The element of array is in comma separated form.

Read from one CSV file and write into the other

The following code read data from a CSV file read.csv and writes the same data to another CSV file readwirte.csv

DOWNLOAD SOURCE CODE

Hope this helps. Thanks.

PHP

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed
  • keusta

    Hello,

    thx for sharing
    i try your exemple it works fine but i would like to know something :

    How to add multiples rows from time to time with a incrementation
    i got a simple form (name, age, gender) and people will submit it from a online page
    i try but this overwrite the previous entry…. maybe i should add an ID row i guess
    but how to detect previous lines ?

    i need your help Mukesh
    ^^
    thx

  • andreasacca

    Hi! This is exactly what I was looking for. This is not the first time I find this blog and everytime I find a solutions to my problems! Thank you for sharing!

  • Ranga

    Hi Mukesh,

    How to put validation and get some data from csv file?