PHP: Reading a CSV file, line by line
Marc Wagner
October 24, 2022
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.
Artikel von:
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.
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?