How To Read A CSV With PHP

Looking how to read a CSV using PHP? What to import a CSV into our database? The code snippet below will help you do just that.

PHP.net has the manual for the fgetcsv which is used in this example.

Example

1
2
3
4
5
6
7
8
9
10
11
12
$row = 1;
if (($handle = fopen("test.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);
}

Replace test.csv with your own file.

This snippet will parse CSV into a multidimensional array

*All code snippets are open source, everyone is free to use.

Please look at our other code snippets Click Here