Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

MerryChristmas's avatar

Problem generating big XML feed

I'm generating big (300MB+) XML feed.

  • Server is not capable holding entire feed in memory. So I occasionally fwrite() into a temp file.

  • Which will successfully generate 300MB+ a file. But when I try to return this file at the end of script, it will memory overflow. Because PHP will try to load this file into a memory to return it.

  • I tried after generating file redirecting to that temp file (works in browser). But XML consumer doesn't support redirects.

I'm capable of generating this file. But I don't know ho to return it without overflowing memory/redirecting to the file? Or how to avoid using a temp file.

0 likes
10 replies
sr57's avatar

But I don't know ho to return it ...

Why? What do you want to do?

Share some code.

MerryChristmas's avatar

@sr57

When you visit the URL you have to first generate fresh data and then return it.

MerryChristmas's avatar

@Sinnbeck

I generate file when the user visits the link. Assume, that there is hundreds of possible feeds and each has 300 MB. It's not possible to pre-generate them and keep them on disk.

So on visiting the link I will generate temp file via fwrite() and return it to user (how? i can't load it via PHP, because of memory overflow; I can't redirect to the file) and ~60s later delete the file.

MerryChristmas's avatar

@Sinnbeck

Problem is when I do traditional

foreach(Products::get() as $product){
						$output . = '........';
}

return $output;

It will just memory overflow.

That's why I went for:

foreach(Products::get() as $product){
					fwrite(...);
}

But now don't know how to return generated file without (1.) redirect (not supported by XML consumer) and (2) without loading it with PHP (yet another memory overflow).

Maybe be instead of occasional fwrite() and generating file I could somehow "stream it" and not hold the entire result in memory?

Sinnbeck's avatar

@MerryChristmas so you are creating the file and sending it in the same request? Why not generate it using a scheduled job?

MerryChristmas's avatar

@Sinnbeck

Because each user (employee) can create unlimited number of his personally structured feeds. I can't keep on disk pre-generated all these feeds. They have to be generated on demand and then thrown away. Or avoid generating file.

MerryChristmas's avatar

@Sinnbeck

Thanks. Looking at these link I came to final code, that seems to work:

 $fs = Storage::disk('public_folder');
$stream = $fs->readStream('/_temp/feed-wholesale.xml');

    return response()->stream(
        function () use ($stream) {
            fpassthru($stream);
        },
        200,
        [
            'Content-Type' => 'application/xml'
        ]
    );

Please or to participate in this conversation.