3

Is it possible to require a php file and get all the things that's echo'ed to be returned and stored into a variable?

Example:

//file1.php
// let's say $somevar = "hello world"
<p><?php echo $somevar; ?></p>


//file2.php
$file1 = getEchoed("file1.php");
// I know getEchoed don't exist, but i'm unsure how to do it.
1

4 Answers 4

12

Use output buffering:

ob_start();
require('somefile.php');
$data = ob_get_clean();
Sign up to request clarification or add additional context in comments.

3 Comments

oops, changed it to use the correct function. always confusing those two.
Don't I need to ob_end() as well, if i want to turn it off?
No. ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().
1

Output buffering can do what you need.

ob_start();
require("file1.php");
$file1 = ob_get_contents();
ob_clean();

Comments

1
ob_start();
include('file1.php');
$contents = ob_get_clean();

The output from file1.php is now stored in the variable $contents.

Comments

0

Output buffering:

<?php

ob_start();

require 'file1.php';

$var_buffer = ob_get_contents();

ob_end_clean();

echo $var_buffer;

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.