3

I am using a PHP include function to add content to an email sent out. Problem is I don't want to echo the file too, I only want to include it as the $message.

Whats the equivalent of include that returns the string without the echo.

$message = include('email/head.php');
Walrus
  • 19,801
  • 35
  • 121
  • 199

3 Answers3

2

Use output buffering.

ob_start();
include('email/head.php');
$message = ob_get_contents();
ob_end_clean();
1

The purpose of include is to evaluate the included file as a PHP file. That means that anything outside of <?php ?> tags is considered output, and it's sent to the browser. If you want to get the content of a file, you need to read it using file_get_contents or fopen/fread.

If you want to evaluate the included file as executable PHP and capture the output, you should use output buffering.

user229044
  • 232,980
  • 40
  • 330
  • 338
0

file_get_contents() will put the full file contents into a variable.

<?php
// grabs your file contents
$email_head = file_get_contents('email/head.php');

// do whatever you want with the variable
echo $email_head ;
?>

Do take into consideration that it will not pre-process head.php as a php file. Therefore file_get_contents() is more suited for static text-files (templates).

Frankie
  • 24,627
  • 10
  • 79
  • 121