Skip to content
Related Articles

Related Articles

Improve Article

How to parse a CSV File in PHP ?

  • Difficulty Level : Medium
  • Last Updated : 21 May, 2021
Geek Week

In this article, we learn to parse a CSV file using PHP code.

Approach:

Step 1. Add data to an excel file. The following example is given for a sample data having Name and Coding Score as their column headers.

Step 2. Convert to CSV file by following the path. Go to File>Export>Change File Type> CSV Type. Save the file in your working folder with name “Book1.csv”.



Parsing CSV file using PHP:

Step 1. Create a folder and add that CSV file and create a new PHP file in it.

file path

Step 2. Open the PHP file and write the following code in it which is explained in the following steps.

  1. Open dataset of CSV using fopen function.

    $open = fopen("filename.csv", "r");
  2. Read a line using fgetcsv() function.

    $data = fgetcsv($Open, 1000, ",");
  3. Use a loop to iterate in every row of data.

    while (($data = fgetcsv($Open, 1000, ",")) !== FALSE) 
    {
      // Read the data    
    }
  4. Close that file using PHP fclose() method.

    fclose($open);

Example:

PHP




<?php
  
  if (($open = fopen("Book1.csv", "r")) !== FALSE) 
  {
  
    while (($data = fgetcsv($open, 1000, ",")) !== FALSE) 
    {        
      $array[] = $data
    }
  
    fclose($open);
  }
  echo "<pre>";
  //To display array data
  var_dump($array);
  echo "</pre>";

Output:

array(6) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "Name "
    [1]=>
    string(12) "Coding Score"
  }
  [1]=>
  array(2) {
    [0]=>
    string(4) "Atul"
    [1]=>
    string(3) "200"
  }
  [2]=>
  array(2) {
    [0]=>
    string(5) "Danny"
    [1]=>
    string(3) "250"
  }
  [3]=>
  array(2) {
    [0]=>
    string(6) "Aditya"
    [1]=>
    string(3) "150"
  }
  [4]=>
  array(2) {
    [0]=>
    string(7) "Avinash"
    [1]=>
    string(3) "300"
  }
  [5]=>
  array(2) {
    [0]=>
    string(6) "Ashish"
    [1]=>
    string(3) "240"
  }
}
My Personal Notes arrow_drop_up
Recommended Articles
Page :