Is it possible to process a CSV file "on the fly" in PHP, line by line, without storing the entire file in memory?
When processing a large CSV file in PHP, it is possible to read and process it line by line without storing the entire file in memory. This can be achieved by using PHP's built-in functions like fopen, fgetcsv, and fclose to open the file, read each line, process it, and then move on to the next line without loading the entire file into memory.
$filename = 'example.csv';
if (($handle = fopen($filename, 'r')) !== false) {
while (($data = fgetcsv($handle)) !== false) {
// Process each line of the CSV file here
// $data is an array containing the values of the current line
// Example: Print the values of the current line
print_r($data);
}
fclose($handle);
} else {
echo "Error opening file.";
}
Keywords
Related Questions
- What is the difference between readdir() and glob() in PHP when it comes to sorting file entries?
- What are potential security risks associated with file uploads in PHP and how can they be mitigated?
- How can one effectively debug and troubleshoot issues related to splitting strings in PHP, as demonstrated in the forum thread?