How can PHP developers efficiently collect output from a script and save it to a file instead of displaying it in the browser?

To efficiently collect output from a script and save it to a file instead of displaying it in the browser, PHP developers can use output buffering. This allows the script's output to be captured and stored in a variable, which can then be saved to a file using file handling functions like fwrite.

<?php
ob_start(); // Start output buffering

// Your script code here

$output = ob_get_clean(); // Get the buffered output and clean the buffer

$file = 'output.txt';
file_put_contents($file, $output); // Save the output to a file
?>