开发者

PHP require return echo?

开发者 https://www.devze.com 2023-02-27 00:43 出处:网络
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?

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.


Use output buffering:

ob_start();
require('somefile.php');
$data = ob_get_clean();


Output buffering can do what you need.

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


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

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


Output buffering:

<?php

ob_start();

require 'file1.php';

$var_buffer = ob_get_contents();

ob_end_clean();

echo $var_buffer;

?>
0

精彩评论

暂无评论...
验证码 换一张
取 消