How can I echo the whole content of a .html file in PHP?
PhpHtmlEchoPhp Problem Overview
Is there a way I can echo the whole content of a .html file in PHP?
For example, I have some sample.html file, and I want to echo that filename, so its content should be displayed.
Php Solutions
Solution 1 - Php
You should use readfile()
:
readfile("/path/to/file");
This will read the file and send it to the browser in one command. This is essentially the same as:
echo file_get_contents("/path/to/file");
except that file_get_contents()
may cause the script to crash for large files, while readfile()
won't.
Solution 2 - Php
Just use:
<?php
include("/path/to/file.html");
?>
That will echo it as well. This also has the benefit of executing any PHP in the file.
If you need to do anything with the contents, use file_get_contents(),
For example,
<?php
$pagecontents = file_get_contents("/path/to/file.html");
echo str_replace("Banana", "Pineapple", $pagecontents);
?>
This doesn't execute code in that file, so be careful if you expect that to work.
I usually use:
include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");
as then I can move files without breaking the includes.
Solution 3 - Php
If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include
or require
. Simply do:
echo file_get_contents("/path/to/file.html");