Tags
Asked 3 years ago
30 Jun 2021
Views 269
Mia

Mia posted

Read large data from csv file in php

Read large data from csv file in php
steave ray

steave ray
answered May 4 '23 00:00

To read large data from a CSV file in PHP, we can use the SplFileObject class that is built into PHP. This class provides an efficient way to read large files by streaming them line by line. Here's an example:



$filename = 'path/to/large.csv';
$file = new SplFileObject($filename, 'r');
$file->setFlags(SplFileObject::READ_CSV);

foreach ($file as $row) {
    // Process each row here
}

In the example above, we first create a SplFileObject instance and pass in the filename of the CSV file we want to read. We then set the file object to read the file as a CSV using the setFlags() method. Finally, we loop through each row in the file and process it as needed.

The advantage of using the SplFileObject class is that it reads the file one line at a time, which means that it can efficiently handle large files without running out of memory.

It's worth noting that the SplFileObject class provides many other useful methods for working with files, such as fgetcsv() for reading a single row from the file, and rewind() for resetting the file pointer to the beginning of the file.
Post Answer