views:

560

answers:

3

So, I'm looking for something more efficient than this:

<?php
ob_start();
include 'test.php';
$content = ob_get_contents();

file_put_contents('test.html', $content);

echo $content;
?>

The problems with the above:

  • Client doesn't receive anything until the entire page is rendered
  • File might be enormous, so I'd rather not have the whole thing in memory

Any suggestions?

+2  A: 

Interesting problem; don't think I've tried to solve this before.

I'm thinking you'll need to have a second request going from your front-facing PHP script to your server. This could be a simple call to http://localhost/test.php. If you use fopen-wrappers, you could use fread() to pull the output of test.php as it is rendered, and after each chunk is received, output it to the screen and append it to your test.html file.

Here's how that might look (untested!):

<?php
$remote_fp = fopen("http://localhost/test.php", "r");
$local_fp = fopen("test.html", "w");
while ($buf = fread($remote_fp, 1024)) {
    echo $buf;
    fwrite($local_fp, $buf);
}
fclose($remote_fp);
fclose($local_fp);
?>
pix0r
A: 

Pix0r's answer is what you want unless you actually need it "included" rather than just executed. For example, if you have login information before the test.php, it will not get passed into the file if you call it with fopen.

If you need it genuinely included, then what you have is the simplest method, but if you want constant output, you'll need to actually write test.php in a manner that outputs as well as stores the information as it goes. As far as I know there's no way to both collect buffer and output it as you go.

UltimateBrent
A: 

Here you go x-send-file, use mod_xsendfile to send file efficiently, really easy.

michal kralik
I'll look into it, but it doesn't address my problem exactly. I want to generate and stream large files from PHP without having to generate the static file first. I'd like to do them in parallel.
Allain Lalonde