PHP: Reading a CSV file, line by line

Marc Wag­ner

Octo­ber 24, 2022

2 min read|

PHP allows you to easi­ly read CSV files line by line using fgetcsv.

fgetcsv #

The fol­lo­wing exam­p­le shows how the who­le 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 func­tion read_csv() takes over the ope­ning of the CSV file and the rea­ding of the indi­vi­du­al lines. The result is then stored in the refe­rence $result. The data is deli­bera­te­ly stored in the refe­rence ins­tead of retur­ning it as an array. This allows us to deter­mi­ne if the func­tion was exe­cu­ted cor­rect­ly or if the file does not exist.

In the exam­p­le abo­ve, we have spe­ci­fied the sepa­ra­tor ‘;’ for the func­tion fgetcsv(). This can be dif­fe­rent and must of cour­se be cho­sen depen­ding on the CSV file.

When rea­ding the file, you should make sure that it con­ta­ins a BOM (Byte Order Mark). If this is the case, it is recom­men­ded to con­vert the file first via e.g. Note­pad++.

Summary #

In PHP, CSV files can be read and edi­ted quick­ly and easi­ly and impor­ted into data­ba­ses, for exam­p­le. Howe­ver, depen­ding on the size of the file, it may be neces­sa­ry to adjust the con­fi­gu­ra­ti­on for the “max_execution_time” in PHP.ini. CSV files are gre­at for trans­fer­ring data quick­ly and easi­ly bet­ween dif­fe­rent sys­tems. Thanks to fgetcsv() CSV files can be read line by line.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar
  1. blank
    Erik Olson Octo­ber 20, 2023 at 17:45 — Rep­ly

    Who would ever read a CSV file deli­mi­t­ed with “;”? Why not just use “,” in your exam­p­le like 9,999,999 out of 10,000,000 users would requi­re?