As other people have mentioned output buffering is probably the cleanest solution here, because it allows you to separate your html template away from your logic. This way you end up with fairly readable html in your template file, instead of a spaghetti code mess.
function render_php($path)
{
ob_start();
include($path);
$var=ob_get_contents();
ob_end_clean();
return $var;
}
Then create your template file
//test.php
<?php for($i = 0; $i<5; $i++):?>
<p><?php echo $i;?></p>
<?php endfor ?>
Then call your function:
render_php('test.php');
You could even make this more reusable by adding a second parameter (an array or object, i.e.
function render_php($path,array $args){
ob_start();
include($path);
$var=ob_get_contents();
ob_end_clean();
return $var;
}
Now lets see how this is useful
//create your template test.php
<?php for($i = $args['start']; $i<$args['end']; $i++):?>
<p><?php echo $i;?></p>
<?php endfor ?>
Now create your arguments and pass them off to the render method
$args = array('start' => 0, 'end' => 5);
render_php('test.php', $args);
Why This is Useful
Now you have a reusable function that is useful, no matter how many arguments you need to pass, and your logic can be in a separate file from your display, making your code a lot more readable. We could use this to build large chunks of html that is still easy to read.
i.e.
$article = array( //imagine we have an article that we have pulled from our database
'title' => 'Some Title',
'subtitle' => 'Some Sub Title',
'body' => 'lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris
eu nulla quis ligula ornare ultricies. Vivamus malesuada lectus a mi
auctor pellentesque. Maecenas eu ultricies sapien, ac porta augue. ',
'image' => 'img/some_image.jpg'
);
echo render_php('article.php',array $article);
and create a template
<!-- article.php -->
<!DOCTYPE html>
<html>
<head>
<title><?php echo $article['title']; ?></title>
</head>
<body>
<img src='<?php echo $article['image']; ?>' alt='whatever' >
<h1><?php echo $article['title']; ?></h1>
<h2><?php echo $article['subtitle']; ?></h2>
<p><?php echo $article['body'];?></p>
</body>
</html>
$string = eval(file_get_contents('test.php'));
You'll need to take out the<?php
and correct the$ < 5
.fopen('php://memory')
andfwrite
instead ofecho
, a bit more to type ( ob control is the php way ) but I you may find than cleaner