Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign the contents of a file to a variable in PHP

Tags:

include

php

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.

like image 888
H. Ferrence Avatar asked Jun 27 '12 15:06

H. Ferrence


People also ask

How can I get the content of a file in PHP?

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.

How can we store variable file in PHP?

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.

What is the difference between file_get_contents () function and file () function?

The file_get_contents() function reads a file into a string. The file_put_contents() function writes data to a file.


2 Answers

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();
like image 137
Tim Cooper Avatar answered Oct 07 '22 01:10

Tim Cooper


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
like image 44
lonesomeday Avatar answered Oct 06 '22 23:10

lonesomeday