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 = include('email_template.php');
When I do a var_dump()
I get string(1) "'"
Is it possible to assign the contents of a file to a variable?
[Note: the reason for doing this is that I want to separate the body segment of a mail message from the mailer script -- sort of like a template so the user just modifies the HTML markup and does not need to be concerned with my mailer script. So I am including the file as the entire body segment on mail($to, $subject, $body, $headers, $return_path);
Thanks.
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.
With ob_get_contents(), you can just get the stuff that was outputted by that other PHP file into a variable. Show activity on this post. file_get_contents() will not work if your server has allow_url_fopen turned off. Most shared web hosts have it turned off by default due to security risks.
The file_get_contents() function reads a file into a string. The file_put_contents() function writes data to a file.
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();
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
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