Processing CSV Files in PHP

Opening the CSV File

To open a CSV file, start by opening the file by using PHP function fopen.

1
$filePointer = fopen(CSV_FILE_PATH, "r"); // Modes: 'r' for read-only, 'w' for write-only, 'a' for append

Reading CSV Data

After opening the file (creating file pointer), cycle through the content using fgetcsv function. This function reads the file line by line and parse it based on fields in CSV.

1
while (($list = fgetcsv($filePointer)) !== FALSE) // looping through each line

Note: Second parameter of fgetcsv must be set to the biggest line in the CSV file in character. By default its value is zero but it would be faster if you know the longest line in your CSV file and specify it.

Complete Example

Here’s a complete example showing how to process a CSV file with headers:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$headerFlag = 0;
$buffer = 10000; // number of character of the longest line in CSV file

while (($list = fgetcsv($filePointer, $buffer)) !== FALSE) { // You can mention delimiter here if your CSV doesn't use comma
    // Skip CSV header
    if ($headerFlag == 0) {
        $headerFlag = 1;
        continue;
    }

    list($col1, $col2, $col3, $col4, $col5) = $list;
    // .... Use $col values
}