3

I want to include a file, but instead of printing output I want to get it as string.

For example, I want include a file:

<?php echo "Hello"; ?> world!

But instead of printing Hello world! while including the file I want to get it as a string.

I want to filter some elements from the file, but not from whole php file, but just from the html output.

Is it possible to do something like this?

  • Yes, using [output buffering](http://www.php.net/manual/en/ref.outcontrol.php); or by modifying your file to return a vaue instead of echoing it – Mark Baker Sep 10 '16 at 10:00
  • @Mark Baker, but if I use ob, will it still print the output or no? –  Sep 10 '16 at 10:01
  • Using output buffering will put the echoed value in the output buffer, not send it to display.... it's up to you what you subsequently do with the contents of that output buffer.... and that can include moving it to a variable rather than displaying it... that's what output buffering is all about – Mark Baker Sep 10 '16 at 10:02
  • Ok, I though that it will print even when buffered. I will try. Thanks –  Sep 10 '16 at 10:04

1 Answers1

5

You can use php buffers like this:

<?php
ob_start();
include('other.php');
$script = ob_get_contents(); // it will hold the output of other.php
ob_end_clean();

EDIT: You can abstract this into a function:

function inlcude2string($file) {
    ob_start();
    include($file);
    $output = ob_get_contents(); // it will hold the output of other.php
    ob_end_clean();
    return $output;
}

$str = inlcude2string('other.php');
jcubic
  • 61,973
  • 54
  • 229
  • 402