Read from and write to a csv file using php

This tutorial shows how to read from a csv file and write to an another csv file. In this example I have shown how to read a csv file and display those values. I have also written those csv entries to another csv file.

Code snippets for reading a csv file

$file_name = "read.csv";
if (($handle = fopen($file_name, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
        echo $data[0] or $data[1] or $data[2] etc.
        //more code
    }
    fclose($handle);
}

 

Code snippets for writing to a csv file

$fp = fopen('write.csv', 'w');

//$infos array containing comma separated values
foreach ($infos as $info) {
    fputcsv($fp, array($info));
}

fclose($fp);

 

Sample data in read.csv file which needs to be read

abc xyz,bdhur@mail.com,20/05/1874
abe xuz,sumaut@mail.com,05/04/1987
dfa jyz,akash@hr.com,04/07/1864
fff hgh,arya.p@tech.com,05/05/1905

 

Source code for reading from read.csv file and write to write.csv file

<?php

$infos = array();
$file_name = "read.csv";
if (($handle = fopen($file_name, "r")) !== FALSE) {
    echo '<table border="1"><thead>';
    echo '<th>Name</th><th>Email</th><th>Date Of Birth</th>';
    echo '</thead>';
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
        echo '<tr><td>' . $data[0] . '</td><td>' . $data[1] . '</td><td>' . $data[2] . '</td></tr>';
        $infos[] = $data[0] . ',' . $data[1] . ',' . $data[2];
    }
    echo '</tbody></table>';
    fclose($handle);
}

$fp = fopen('write.csv', 'w');

foreach ($infos as $info) {
    fputcsv($fp, array($info), ',', ' ');
}

fclose($fp);
/*
 * End of csvparser.php
 */

 

Output file write.csv file

 abc  xyz,bdhur@mail.com,20/05/1874
 abe  xuz,sumaut@mail.com,05/04/1987
 dfa  jyz,akash@hr.com,04/07/1864
 fff  hgh,arya.p@tech.com,05/05/1905

 

That’s all. Thanks for your reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin

2 Replies to “Read from and write to a csv file using php”

  1. I have a scenario wherein admns from other departments can upload a (csv) file to server. Data structure is
    name,date,comments. Here in the details column, there may be many occurrences of comma.
    Example.
    Tom,3/12/2017, Logged the data, ordered 14 pieces

    As you can see there is comma in the 3rd field.

    As a super user, I need to read the csv file,check this column and replace comma with another char and then load in mysql db.

    Can you tell me how to do?

Leave a Reply

Your email address will not be published. Required fields are marked *