Writing Include to Variable in PHP
Let's say we have a file:
<div>
<?= 'test' ?>
</div>
Let's write the text of our file into a variable in the main file:
<?php
$res = file_get_contents('test.php');
?>
However, we will have a problem - when writing to a variable, the PHP code of our file will not be executed.
In order for the PHP code of the included file
to be executed, you need to use the
include
operator. The problem, however, is that
this operator immediately outputs data to the
screen, so the result of the inclusion cannot
be written to a variable.
But it is still possible to do this if you use a clever trick:
<?php
ob_start();
include 'test.php';
$res = ob_get_clean();
?>
Let's format the code of the trick into a function:
<?php
function getFile($name) {
ob_start();
include $name;
return ob_get_clean();
}
?>
Let's use our function to get the file into a variable:
<?php
$res = getFile('test.php');
echo 'index' . $res;
?>
Create a file that will generate a dropdown list of days of the week from an array. Write the result to a variable in your main file. Output this variable in several places in the file.