Whenever a script takes some time, the server (Apache) attempts to send it as being a download. It doesn't have this issue once the time-intensive loop within the file is created shorter, implying it's simply the size of script execution that's leading to the issue.

I've timeout set to infinite in PHP, kind it's delivering like a download rather than running?