Search the blog

To get what PHP has output so far as a string you need to make use of output buffering. Switching on output buffering tells PHP top stop sending data to the browser piecemeal. Instead, you can fetch it manually.

Once the script terminates, PHP will send whatever is in the output buffer to the browser.

The output buffer is managed with the ob_ functions. Here’s an example:

// Start OB

// echo whatever you want
// ...

$html = ob_get_contents();

// Do what you want with $html E.g.
file_put_contents('./cache/index.html', $html);
Tim Bennett is a freelance web designer from Leeds. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.