1

example i have a file template.php with:

<table>
    <tr>
        <td><?php echo $data['nombre'] ?></td>
    </tr>
    <?php foreach($data['values] as $value): ?>
    <tr>
        <td><?php echo $value ?> </td>         
    </tr>
    <?php endforeach; ?>
</table>

and i need the result into a string $result = get_content_process('template.php',$data); for use in other process.

echo $result;
<table>
    <tr>
        <td>Juan</td>
    </tr>
    <tr>
        <td>Male</td>         
    </tr>
    <tr>
        <td>Brown</td>         
    </tr>
</table>
hakre
  • 193,403
  • 52
  • 435
  • 836
rkmax
  • 17,633
  • 23
  • 91
  • 176
  • 2
    could be useful -- http://stackoverflow.com/questions/2832010/what-is-output-buffering – ajreal Sep 02 '11 at 19:09
  • Also related: [Modify an Existing PHP Function to Return a String](http://stackoverflow.com/q/8730847/367456) – hakre Aug 04 '12 at 09:24

4 Answers4

3
<?php
ob_start();
include 'template.php';
$result = ob_get_clean()
?>

this should do, the $result is the string you need

beerwin
  • 9,813
  • 6
  • 42
  • 57
  • if you need to know, it's called output buffering, and it comes very handy when you have to generate and process data in the same script – beerwin Sep 02 '11 at 19:37
1

To make sure you don't flush early, turn implicit flush off. This function should do the trick:

function get_content_process($template, $data) {
   ob_implicit_flush(false);
   include($template);
   $contents = ob_get_contents();
   ob_clean();
   ob_implicit_flush(true);
   return $contents;
}
regality
  • 6,496
  • 6
  • 29
  • 26
0

You can use ob_start() to do something like this

<?php
    ob_start( );
    $GLOBALS['data'] = ...;
    include("template.php");
    $result = ob_get_clean();
    echo $result;
?>
Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
0

simple and fast solution:

$result = file_get_contents($view); // $view == the address of the file(ie 'some_folder/some_file.php')
Pawan Choudhary
  • 1,073
  • 1
  • 10
  • 20