How to Save Output of a PHP File in an HTML File

Saving dynamic page content in a static HTML file functionality is used for many purposes, page caching system is one of them. In the caching system, the dynamic data is stored in an HTML file and displays the content from the HTML file to make the page load faster. In this example code snippet, we will show you how to save output of a PHP file in an HTML file and store dynamic page content in an HTML file using PHP.

Execute the code of a PHP file and save output in an HTML file:
The following code will execute a PHP file (my_script.php) and store the output in an HTML file (static_content.html).

  • Start output buffering using the PHP ob_start() function.
  • Get content of output buffer using PHP ob_get_contents() function.
  • Use the file_put_contents() function to save the output of the PHP file.
  • End and clean output buffering using PHP ob_end_clean() function.
// Start output buffering 
ob_start();

include 
'my_script.php';

// Save captured output to file
file_put_contents('static_content.html'ob_get_contents());

// End output buffering
ob_end_clean();

Execute PHP file and get content in a variable:
The following code will execute the code of a PHP file and store output in a variable.

// Start output buffering 
ob_start();

include 
'my_script.php';

// Save captured output in variable
$output ob_get_clean();

// End output buffering
ob_end_clean();

Leave a reply

keyboard_double_arrow_up