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
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();