-3

I'm trying to read a CSV file that has 800000 line using PHP, but i got this Error:

Allowed memory size of 536870912 bytes exhausted (tried to allocate 4096 bytes)

How could i fix it?

El-Hani
  • 163
  • 9
  • you should read file in chunks please share the code what you have tried. – Dhaval Purohit Nov 27 '19 at 07:16
  • 1
    Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Bartosz Zasada Nov 27 '19 at 07:17
  • One simple google search can leads to direct answer ... https://stackoverflow.com/questions/17520093/read-large-data-from-csv-file-in-php – EternalSunShine Nov 27 '19 at 07:20
  • A common cause is either reading the whole file in one go or storing all of the data in an array. You need to process it as you go along (whenever possible). – Nigel Ren Nov 27 '19 at 07:22
  • 2
    Does this answer your question? [file\_get\_contents => PHP Fatal error: Allowed memory exhausted](https://stackoverflow.com/questions/5249279/file-get-contents-php-fatal-error-allowed-memory-exhausted) – Maximouse Nov 27 '19 at 08:05
  • Did you read the CSV data then insert to database? – Malca Nov 27 '19 at 08:15

1 Answers1

1

You can read it by chunk.

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

LF00
  • 27,015
  • 29
  • 156
  • 295