How to import csv file in PHP?

The below code can be used to import CSV file in 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>
";       $row++;       for ($c=0; $c < $num; $c++) {          echo $data[$c] . "<br />
";       }    }    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.

Updated on: 09-Apr-2020


Kickstart Your Career

Get certified by completing the course

Get Started