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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP fgetcsv() to Read and Parse CSV Files

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);
}
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendTutorialfile-handlingfgetcsv
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.