PHP read CSV file line by lines

PHP read CSV file line by lines

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP read CSV file line by lines

Reading a CSV file from a remote URL requires shifting your mental model from "loading everything into memory" to "streaming data." When you need to process rows individually, attempting to load the entire file via file_get_contents() is usually an anti-pattern. It consumes excessive RAM and creates unnecessary garbage collection pressure if the dataset grows large. The goal is to fetch a chunk of bytes and parse them incrementally without holding the whole result in memory.

The specific line structure you provided reveals two immediate complexities: semicolon delimiters and quoted fields containing commas or special characters.

1004000018;active;"TEST1";"TEST2";"TEST3";"TEST4" 

A naive explode() based on the semicolon delimiter will fail immediately because the quoted fields might contain internal delimiters, or conversely, if the separator changes mid-file. You must respect the CSV specification strictly.

The Streaming Approach with cURL

To fetch and process a remote CSV, you combine cURL with line-by-line reading logic. This ensures you only hold one line in memory at any given moment.

$ch = curl_init('https://example.com/data.csv');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
]);

while ($line = curl_read_line($ch)) {
    if (empty(trim($line))) {
        continue; // Skip empty lines
    }

    $parsed = parseCSVLine($line);
    // Process parsed data here
}

curl_close($ch);

The critical missing piece in the snippet above is how parseCSVLine handles the quoted fields. Standard string functions like str_replace or regex are insufficient for robust CSV parsing. You need a parser that understands the state machine: it knows when it is inside quotes, so it ignores semicolons found within those quotes.

Using the Built-in Parser

PHP's standard library does not include a dedicated CSV parser in the core SAPI (though fgetcsv exists for file streams, handling remote URLs requires a slight wrapper). However, you can leverage fgetcsv by piping the cURL stream directly to a file handle or using a custom iterator.

A more direct approach for single-line processing without external dependencies is writing a small parser function that respects quotes:

function parseCSVLine(string $line): array {
    $fields = [];
    $field = '';
    $inQuotes = false;
    $length = strlen($line);
    $i = 0;

    while ($i < $length) {
        $char = $line[$i];

        if ($char === '"' && !$inQuotes) {
            $inQuotes = true;
        } elseif ($char === '"' && $inQuotes) {
            // Check for escaped quote ""
            if ($i + 1 < $length && $line[$i + 1] === '"') {
                $field .= '"';
                $i++;
            } else {
                $inQuotes = false;
            }
        } elseif ($char === ';' && !$inQuotes) {
            $fields[] = trim($field);
            $field = '';
        } else {
            $field .= $char;
        }

        $i++;
    }

    // Push the last field
    $fields[] = trim($field);

    return $fields;
}

This logic handles your specific example correctly. When it encounters "TEST1", it treats the internal semicolon (if any) as part of the value because $inQuotes is true, effectively isolating the field before looking for the next delimiter outside the quotes.

Trade-offs and Pitfalls

The primary trade-off here is performance versus library dependency. Using a dedicated CSV parser class (like League\Csv) is often safer but introduces an external dependency and requires loading the entire stream or buffering logic that might defeat the purpose of true streaming if not implemented carefully.

A common mistake developers make when processing remote CSVs is ignoring the HTTP status code. If the server returns a 403 or 500, your loop will spin waiting for a line that never arrives. Always wrap your cURL fetch in a try-catch block and verify $ch has data before entering the parsing loop.

Another subtle issue is encoding. CSV files fetched from URLs might be UTF-8 but lack the BOM (Byte Order Mark), or they might contain Windows-style line endings (\r\n). Your parser should ideally normalize line endings before processing to avoid off-by-one errors in index calculations, although the character-by-character approach shown above naturally handles mixed line endings without explicit splitting.

For production environments where you need more robust error handling (like skipping malformed rows or logging parse failures), consider integrating a library such as League\Csv. While the custom function offers zero-dependency parsing for simple cases like your example, real-world data often contains edge cases—such as fields that start with quotes but aren't closed properly—that require the state-machine logic found in established libraries.

If you are building a larger ecosystem around this logic, resources from https://laravelcompany.com offer insights into handling large datasets efficiently within Laravel's collection system, though for raw streaming performance, native PHP streams remain the most lightweight solution.

Our network