Search code examples
phpinclude

Include a php file, but return output as a string instead of printing


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?


Solution

  • You can use php buffers like this:

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

    You can abstract this into a function:

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