Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning contents to a variable with include/require_once

Is it possible to do like

$var = require_once('lol.php');

so that any HTML output that lol.php does will go inside $var?

I know about output buffering, but is there some special built-in function that already does this?

like image 962
Alex Avatar asked Oct 16 '11 18:10

Alex


People also ask

How do you include a variable?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.

How to include file path in PHP?

PHP Include Files. The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.


2 Answers

$var = require_once('lol.php'); will only put the return value of the file into $var. If you don't return anything from it, it'll just be null.

If you want the output you will need to use output buffering:

ob_start();
require_once('lol.php');
$var = ob_get_clean();
like image 108
NikiC Avatar answered Oct 15 '22 00:10

NikiC


The assignment from an =include() call will only get you a possible return value from that script, not any output.

To make this possible you would have to modify the include script to capture the output:

 <?php
      ob_start();

      ...

      return ob_get_clean();
 ?>
like image 37
mario Avatar answered Oct 15 '22 02:10

mario