How To Read CSV File Using PHP

How To Read CSV File Using PHP

php csv parser


When Creating Business Tool for any Company or ERP System Sometime we Need to Parse the csv data of Clients  which contains informations of companies like products, survey anything that comes in csv.

Now How We Parse Such types of Data and Create a new file from that or Show the Current file Data.?

Let's Start today we See.

1.How to Open CSV file.
2.How to read CSV files rows data.
3.How to  Create CSV file using php.

Let's Do it...


First php had Two prebuild function for reading csv file and writing data in CSV files.

For Reading Data
1.fgetcsv(file,length,separator,enclosure);

file (Required)  current open file.
length (optional) length of file.
separator (Optional) character that specifies the field. ( , ) comma is default.
enclosure  (Optional) character that specifies the field enclosure character

For Writing Data
2. fputcsv(file,fields,separator,enclosure);
file (Required)  current open file.
fields (Required) simple array of data.
separator (Optional) character that specifies the field. ( , ) comma is default.
enclosure  (Optional) character that specifies the field enclosure character
 Now Let's Create a Demo Example in which i create a PHP file which open a csv and read the data the use its two column (id,name) and create a another csv file. Also i display the current csv file which i am opening.

Code : 

<?php

/*=========================================================================================
 || Function for Opening CSV File and Read its Data with title and Data contents         ||
==========================================================================================*/

function csv_to_php_array($file)
{
     //=========opening file======
    $files = fopen($file, "r");

    //=========decalring two array for title and data=============
    $array = array();
    $title = array();
    $i     = 0;


    //===============running loop until not reached the end of file============
    while (!feof($files)) {

      //=======if loop running first time then it will be its title so storing in title===========
        if ($i == 0) {

          //==================increase value 1 so it dont run again===================
            $i    = 1;
            $data = fgetcsv($files);
            array_push($title, $data);
            continue;
        }

        //========after title when loops runs it stores data in data array=======================
        $data = fgetcsv($files);
        array_push($array, $data);
        
    }

    //==================closing the file after work==================================
    fclose($files);

    //================returning the contents of file===============================
    return array(
        "title" => $title,
        "data" => $array
    );
}
/*=========================================================================================
 || End Of Function                                                                      ||
==========================================================================================*/

//=================calling the function of csv=========================
$filedata = (csv_to_php_array("sample.csv"));

//==============getting titles====================
$titles   = $filedata['title'][0];

//================getting datas=====================
$datas    = $filedata['data'];

//=================opening new file for writing our new data which is only id and name.============
$newfile  = fopen("newfile.csv", "w");

//=================putting the heading title of new csv file===================
fputcsv($newfile, array(
    "id",
    "name"
));

//========================creating table which disaplay our csv file in browser================
echo "<table style='border:1px solid green;border-collapse:collapse;' border='1'>";
echo "<tr>";

//===============running loop until all title not print==============
foreach ($titles as $title) {
    echo "<th>" . $title . "</th>";
}
echo "</tr>";

//=================running loop for each row of data====================
foreach ($datas as $data) {

  //=================store data in new csv which is id and name in array index 0 and 2 respectively.
    fputcsv($newfile, array(
        $data[0],
        $data[2]
    ));

    //=================printing each cell data of rows======================
    echo "<tr>";
    foreach ($data as $cell) {
        echo "<td>" . $cell . "</td>";
    }
    echo "</tr>";
    
}
//=================closing our new created file=============================
fclose($newfile);

Output Result : 

php csv
 

Download Dummy CSV File Link

 
Previous Post
Next Post

post written by:

0 comments: