Is there a native function or set of functions in PHP that will allow me to echo
and print php file output into file.
For example code will generate HTML DOM that needs to be put into .html file and then displayed as static page.
The echo command is used in PHP to print any value to the HTML document. Use <script> tag inside echo command to print to the console.
If it is turned on then stdout output will still go to the standard output of the console/browser but php://output will go to the buffer until the buffer reaches it's capacity or you manually flush the buffer.
Open a file using fopen() function. Get the file's length using filesize() function. Read the file's content using fread() function. Close the file with fclose() function.
The easiest method would be to create a string of your HTML data and use the file_put_contents()
function.
$htmlStr = '<div>Foobar</div>';
file_put_contents($fileName, $htmlStr);
To create this string, you'll want to capture all outputted data. For that you'll need to use the ob_start
and ob_end_clean
output control functions:
// Turn on output buffering
ob_start();
echo "<div>";
echo "Foobar";
echo "</div>";
// Return the contents of the output buffer
$htmlStr = ob_get_contents();
// Clean (erase) the output buffer and turn off output buffering
ob_end_clean();
// Write final string to file
file_put_contents($fileName, $htmlStr);
Reference -
ob_start()
ob_get_contents()
ob_end_clean()
file_put_contents()
PHP output control documentation
file_put_contents($filename, $data)
http://php.net/manual/en/function.file-put-contents.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With