Computer >> Computer tutorials >  >> Programming >> PHP

How to parse a CSV file using PHP


To parse a CSV file in PHP, the code is as follows. Under fopen(), set the path of the .csv file−

Example

$row_count = 1;
if (($infile = fopen("path to .csv file", "r")) !== FALSE) {
   while (($data_in_csv = fgetcsv($infile, 800, ",")) !== FALSE) {
      $data_count = count($data_in_csv);
      echo "<p> $data_count in line $row_count: <br /></p>\n";
      $row_count++;
      for ($counter=0; $counter < $data_count; $counter++) {
         echo $$data_in_csv[$counter] . "<br />\n";
      }
   }
   fclose(infile);
}

Code explanation − The file can be opened in reading mode (if it exists) and until a specific threshold length, it can be read and displayed. The row_count counter can be incremented to parse the next line in the file.

Output

The input CSV file will be parsed and displayed line by line.

For PHP version>=5.3.0, the below code can be used−

$file_to_read = file('path to .csv file');
$data_to_ingest = [];
foreach ($file_to_read as $infile) {
   $data_to_ingest[] = str_getcsv(infile);
}

Note − This wouldn’t work if the CSV file has any new line characters since the logic is that the function splits the newlines and doesn’t identify quotation marks.