PHP: Reading a CSV file, line by line

Table of Contents

PHP allows you to easily read CSV files line by line using fgetcsv.

fgetcsv #

The following example shows how the whole thing works with fgetcsv:

/**
 * Reading a CSV file with fgetcsv
 * 
 * @param string $path_to_csv_file    The path to the CSV file
 * @param array &$result              Stores the data in the reference variable.
 */
function read_csv(string $path_to_csv_file, array &$result): bool{
    $handle = fopen($path_to_csv_file, 'r');
    
    if(!$handle){
       return false;
    }

    while(false !== ($data = fgetcsv($handle, null, ';'))){
       $result[] = $data;
    }
    
    return true;
}

$response = [];
if(!read_csv('/path/to/file.csv', $response)){
   echo "CSV file could not be opened.";
}

foreach($response as $row_number => $data){
   echo $row_number.': '.$data[0];
}

The function read_csv() takes over the opening of the CSV file and the reading of the individual lines. The result is then stored in the reference $result. The data is deliberately stored in the reference instead of returning it as an array. This allows us to determine if the function was executed correctly or if the file does not exist.

In the example above, we have specified the separator ‘;’ for the function fgetcsv(). This can be different and must of course be chosen depending on the CSV file.

When reading the file, you should make sure that it contains a BOM (Byte Order Mark). If this is the case, it is recommended to convert the file first via e.g. Notepad++.

Summary #

In PHP, CSV files can be read and edited quickly and easily and imported into databases, for example. However, depending on the size of the file, it may be necessary to adjust the configuration for the “max_execution_time” in PHP.ini. CSV files are great for transferring data quickly and easily between different systems. Thanks to fgetcsv() CSV files can be read line by line.

Hier klicken, um den Beitrag zu bewerten
[Gesamt: 1 Durchschnitt: 5]

One Comment

  1. Avatar of Erik Olson
    Erik Olson October 20, 2023 at 17:45 - Reply

    Who would ever read a CSV file delimited with “;”? Why not just use “,” in your example like 9,999,999 out of 10,000,000 users would require?

Leave A Comment

Title