Reputation: 12297
Every time I try to assign an include/require to a variable, it adds a number at the end. I would like to do it without that stupid number.
I tried file_get_contents but it does not work the same way. If it's not possible to do it with require, is there an EASY and SHORT (Single function and single line of code) way to do it with another function?
Please help me, because it's driving me crazy.
For example:
FILE 1 (div.php):
<div><?php echo $x; ?></div>
FILE 2:
<?php
$x = "Example 1";
$file = include('div.php');
echo $file;
$x = "Example 2";
$file = include('div.php');
echo $file;
?>
OUTPUT:
Example 1 1 Example 2 1
Upvotes: 2
Views: 564
Reputation: 160863
If you use FILE1 as the template, just include it. Also you can use output buffering as @grossvogel answered.
<?php
$x = "Example 1";
include('div.php');
$x = "Example 2";
include('div.php');
?>
Upvotes: 0
Reputation: 41551
This is because the default return value of include
and require
is true
, or 1
.
When you include the file, it automatically outputs your content in the included file. When you echo $file
, you are echoing the return value of the include, which is true
.
As a note, if you put return false;
or return "<div>$x</div>";
in your included file, that would then become the value of $file
. Whatever you return from your included file, that is passed to the variable.
For example:
FILE 1 (monkey_do.php):
<?php
return "I am a monkey";
FILE 2 (main.php):
<?php
$monkey_see = include 'monkey_do.php';
echo $monkey_see; // prints "I am a monkey"
Upvotes: 6
Reputation: 6782
You could use output buffering:
$x = 'Example 1';
ob_start();
include ('div.php');
$file = ob_get_contents();
ob_end_clean();
echo $file;
EDIT: I just saw this example in the manual that defines a function to do this: http://php.net/manual/en/function.include.php#example-131
Upvotes: 1