Read CSV file using PHP

  •  
  •  
  •  
  •  
  •  
  •  

Read CSV file using PHP is very easy and simple. PHP has a built function fgetcsv(), through which we can read CSV file easily. So, in this tutorial, I will teach how to read CSV file using PHP. Friends, if you want to know how to write data into CSV file using PHP, please visit my previous tutorial.

Read CSV file using PHP

HTML code – Read CSV file using PHP

<div class="contentDiv">
  <form action="" method="post" enctype="multipart/form-data">
    Upload CSV : <input type="file" name="uploadFile" id="uploadFile" value="" /> 
           <input type="submit" name="submitBtn" id="submitBtn" value="Upload" />
  </form>
</div>

Create a PHP file “index.php” in the root folder and write the above HTML code in it. Above code contains one HTML file element and a submit button. The code is very simple.

PHP and HTML code – Read CSV file using PHP

<?php
if(isset($_POST['submitBtn'])) {
  $file = fopen($_FILES['uploadFile']['tmp_name'], "r");
  ?>
  <table id="100%" cellpadding="5" cellspacing="1">
    <tbody>
      <tr>
        <th>SL.</th>
        <th>NAME</th>
        <th>MOBILE</th>
        <th>COUNTRY</th>
      </tr>

  <?php
  //Loop through the CSV rows.
  while (($row = fgetcsv($file, 0, ",")) !== FALSE) {
    //Print out my column data.
    ?>
    <tr>
      <td><?php echo $row[0]; ?></td>
      <td><?php echo $row[1]; ?></td>
      <td><?php echo $row[2]; ?></td>
      <td><?php echo $row[3]; ?></td>
    </tr>	
    <?php
  }
  fclose($file);
  ?>
  </tbody>
<?php
}
?>

Append the above code after the previous HTML code in the index.php file. When a user uploads a CSV file and clicks the submit button it executes the above code.

Read CSV file using PHP

$file = fopen($_FILES['uploadFile']['tmp_name'], "r");

This line of code opens the uploaded CSV file in read mode.

//Loop through the CSV rows.
while(($row = fgetcsv($file, 0, ",")) !== FALSE) {
  //Print out my column data.
  ?>
  <tr>
    <td><?php echo $row[0]; ?></td>
    <td><?php echo $row[1]; ?></td>
    <td><?php echo $row[2]; ?></td>
    <td><?php echo $row[3]; ?></td>
  </tr>	
<?php
}

fgetcsv($file, 0, “,”) parses each line from the open CSV file. “0” means, the line length is not limited. “,”  is the separator. In a CSV file, all values are separated by the comma, whereas individual rows are separated by new lines. fgetcsv() returns an array on success or false on failure.

Download the full source code from the below download link and please like and share this tutorial link to others.

 

About Mitrajit

Leave a Reply

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

Prove you are a human *