Loop through the txt file in a folder and read the data into the database by row. The error message "Fatalerror: Allowedmemorysizeof134217728bytesexhausted" is displayed. The Code is as follows. Each txt file is not large (about KB ), and it's moving... loop through the txt file in a folder and read the data into the database by row. The error message "Fatal error: Allowed memory size of 134217728 bytes exhausted" appears,
The Code is as follows. Each txt file is not large (about KB) and is read by row. Why?
$ File = new \ FilesystemIterator ($ fileName); foreach ($ file as $ fileinfo) {if ($ fileinfo-> isFile () {$ fp = fopen ($ fileName. '/'. $ fileinfo-> getFilename (), 'R'); while (! Feof ($ fp) {$ data ['score '] = 7; $ data ['code'] = fgets ($ fp ); $ this-> book-> add ($ data); // save to database} fclose ($ fp );}}
Reply content:
Loop through the txt file in a folder and read the data into the database by row. The error message "Fatal error: Allowed memory size of 134217728 bytes exhausted" appears,
The Code is as follows. Each txt file is not large (about KB) and is read by row. Why?
$ File = new \ FilesystemIterator ($ fileName); foreach ($ file as $ fileinfo) {if ($ fileinfo-> isFile () {$ fp = fopen ($ fileName. '/'. $ fileinfo-> getFilename (), 'R'); while (! Feof ($ fp) {$ data ['score '] = 7; $ data ['code'] = fgets ($ fp ); $ this-> book-> add ($ data); // save to database} fclose ($ fp );}}
Use the keyword yield for iterative operations. It does not store intermediate variables to save memory and requires php5.5 +
$ This-> book-> add ($ data );
Unset ($ data );
During the while LOOP, $ data will be copied at write time (COW), and the memory will be released only after your script is executed.
Install xdebug or xhprof to view the performance analysis report.
I guess it is the framework configuration, and SQL is collected.