How to import csv file in PHP?

PHPServer Side ProgrammingProgramming

The below code can be used to import CSV file in PHP −

<?php
$row = 1;
if (($handle = fopen("name_of_file.csv", "r")) !== FALSE) {
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
      $num = count($data);
      echo "<p> $num fields in line $row: <br /></p>\n";
      $row++;
      for ($c=0; $c < $num; $c++) {
         echo $data[$c] . "<br />\n";
      }
   }
   fclose($handle);
}
?>

The file will display the contents of the csv file are displayed on the screen.

In the above code, beginning from row 1 (since row 0 would usually contain headers/column names), the csv file is opened in read mode and the fgetcsv function is called to read in 1000 rows of data present in the csv file.

The number of columns in every row is displayed along with the contents of it.

raja
Published on 09-Apr-2020 14:09:49
Advertisements