Long-running PHP memory overflow.

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.