I have a document file containing HTML markup. I want to assign the contents of the entire file to a PHP variable.
I have this line of code:
$body = in
You have two optional choices
[Option 1]
'email_template.php'
inside the file add a variable like so
$body = '<html>email content here</html>';
in another file require_once 'email_template.php'
echo $body;
[Option 2]
$body = require_once 'email_template.php';
file_get_contents()
$file = file_get_contents('email_template.php');
Or, if you're insane:
ob_start();
include('email_template.php');
$file = ob_end_flush();
Try using PHP's file_get_contents()
function.
See more here: http://php.net/manual/en/function.file-get-contents.php
If there is PHP code that needs to be executed, you do indeed need to use include
. However, include
will not return the output from the file; it will be emitted to the browser. You need to use a PHP feature called output buffering: this captures all the output sent by a script. You can then access and use this data:
ob_start(); // start capturing output
include('email_template.php'); // execute the file
$content = ob_get_contents(); // get the contents from the buffer
ob_end_clean(); // stop buffering and discard contents
As others have posted, use file_get_contents
if that file doesn't need to be executed in any way.
Alternatively you can make your include return the output with the return statement.
If your include does processing and outputs with echo [ed: or leaving PHP parsing mode] statements you can also buffer the output.
ob_start();
include('email_template.php');
$body1 = ob_get_clean();
TimCooper beat me to it. :P
You should be using file_get_contents():
$body1 = file_get_contents('email_template.php');
include is including and executing email_template.php
in your current file, and storing the return value of include()
to $body1
.
If you need to execute PHP code inside the of file, you can make use of output control:
ob_start();
include 'email_template.php';
$body1 = ob_get_clean();