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

include, php

Solution

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

Problem

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.

Original source