正如其他人所提到的输出缓冲可能是干净的解决方案在这里,因为它可以让你的HTML模板远离你的逻辑中分离出来。这样你最终会在模板文件中获得相当可读的html,而不是意大利面条代码混乱。通过添加第二个参数(数组或对象,即
render_php('test.php');
你甚至可以让这个更可重复使用:
function render_php($path)
{
ob_start();
include($path);
$var=ob_get_contents();
ob_end_clean();
return $var;
}
然后创建模板文件
//test.php
<?php for($i = 0; $i<5; $i++):?>
<p><?php echo $i;?></p>
<?php endfor ?>
然后调用你的函数
function render_php($path,array $args){
ob_start();
include($path);
$var=ob_get_contents();
ob_end_clean();
return $var;
}
现在让我们看看这是怎么有用
//create your template test.php
<?php for($i = $args['start']; $i<$args['end']; $i++):?>
<p><?php echo $i;?></p>
<?php endfor ?>
现在创建你的论点,并通过他们关闭的渲染方法
$args = array('start' => 0, 'end' => 5);
render_php('test.php', $args);
为什么这是有用的
现在你有一个可重复使用的功能这是非常有用的,不管你需要传递多少个参数,并且你的逻辑可以在你的显示器的独立文件中,使你的代码更具可读性。我们可以使用它来构建仍然易于阅读的大块html。
即
$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);
,并创建一个模板
<!-- 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>
看看http://php.net/manual/en/function.eval.php。例如我想你想要'$ string = eval(file_get_contents('test.php'));'你需要取出'<?php'并更正'$ <5'。 – chris85
“我知道ob_start()解决方案,但它感觉很脏”为什么?据我所见,这就是你想要的? – PeeHaa
在这种情况下,@Peehaa是对的 - 你有你的解决方案,并且它有一个存在于php中的理由 - 供你使用它。 – somethinghere