PHP: Reading a CSV file, line by line

Marc Wagner, October 24, 2022
Table of Contents

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.

Avatar of Marc Wagner
Marc Wagner

Hi Marc here. I'm the founder of Forge12 Interactive and have been passionate about building websites, online stores, applications and SaaS solutions for businesses for over 20 years. Before founding the company, I already worked in publicly listed companies and acquired all kinds of knowledge. Now I want to pass this knowledge on to my customers.

Similar Topics

Comments

  1. 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?

Leave A Comment