Using PHP fgetcsv() to Read and Parse CSV Files
This article explains the PHP fgetcsv() function, its parameters, return values, and provides a complete example showing how to open a CSV file, read each line as an array of fields, and process the data in a backend script.
fgetcsv() reads a line from an open file pointer, parses it as CSV, and returns an array of fields.
It works similarly to fgets() but automatically splits the line according to the specified delimiter, enclosure and escape characters. The function signature is
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]]] ).
Parameters: $handle – a valid file pointer from fopen(), popen() or fsockopen(); $length – maximum line length (optional, 0 means no limit); $delimiter – field separator (single character); $enclosure – field enclosure character; $escape – escape character (default backslash).
Return value: an indexed array of fields, NULL on invalid handle, FALSE on EOF or error.
Example usage:
<?php
$handle = fopen('test.csv', 'r');
if ($handle !== FALSE) {
$row = 1;
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
$num = count($data);
echo "<p>$num fields in line $row:<br/></p>
";
$row++;
for ($c = 0; $c < $num; $c++) {
echo $data[$c] . "<br />
";
}
}
fclose($handle);
}
?>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
