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

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

Tags:

Php

Include