2009-08-21 116 views
8

我搞砸了模板,我遇到了一种情况,我需要回显浏览器包含html & php的模板。我如何评估PHP并将其发送到浏览器?PHP Eval,评估HTML和PHP

所以这里有一个例子(main.php):

<div id = "container"> 
     <div id="head"> 
      <?php if ($id > 10): ?> 
       <H3>Greater than 10!</H3> 
      <?php else: ?> 
       <H3>Less than 10!</H3> 
      <?php endif ?> 
     </div> 
      </div> 

然后在的template.php:

<?php 
      $contents; // Contains main.php in string format 
      echo eval($contents); // Doesn't work... How do I do this line?? 
    ?> 

编辑:我的模板,也可以让你从控制器注入数据Smarty的风格。输出缓冲区允许我这样做,然后评估我的PHP。理想的是,它首先完成代码并首先评估所有标记,然后运行php。这样我就可以创建循环和使用从我的控制器发送的数据。

So maybe a more complete example: 
    <div id = "container"> 
      <div id = "title">{$title}</div> <!-- This adds data sent from a controller --> 
      <div id="head"> 
       <?php if ($id > 10): ?> 
        <H3>Greater than 10!</H3> 
       <?php else: ?> 
        <H3>Less than 10!</H3> 
       <?php endif ?> 
      </div> 
    </div> 

谢谢!

回答

10

改为使用输出缓冲。 eval()臭名昭彰缓慢。

main.php

<div id="container"> 
    <div id="title"><?php echo $title; ?></div><!-- you must use PHP tags so the buffer knows to parse it as such --> 
    <div id="head"> 
     <?php if ($id > 10): ?> 
      <H3>Greater than 10!</H3> 
     <?php else: ?> 
      <H3>Less than 10!</H3> 
     <?php endif ?> 
    </div> 
</div> 

您的文件:

$title = 'Lorem Ipsum'; 
$id = 11; 

ob_start(); 
require_once('main.php'); 
$contents = ob_get_contents(); 
ob_end_clean(); 

echo $contents; 

这样做的结果应该是:

Lorem存有

大于10!

+0

我澄清我的模板做什么,就这还工作吗? – Matt 2009-08-21 02:35:54

+0

是的,你可以使用你已经在模板中声明的变量。不过,您不能像使用{$ title}那样使用{$ title},只会从字面上显示文本。你必须告诉模板那是PHP。我已经更新了我的回答来演示。 – 2009-08-21 03:47:31

+0

这个答案应该被接受! – 2014-07-16 16:15:35

2

不读取文件,但包含它并使用输出bufferig捕获结果。

ob_start(); 
include 'main.php'; 
$content = ob_get_clean(); 

// process/modify/echo $content ... 

编辑

使用函数生成一个新的变量范围。

function render($script, array $vars = array()) 
{ 
    extract($vars); 

    ob_start(); 
    include $script; 
    return ob_get_clean(); 
} 

$test = 'one'; 
echo render('foo.php', array('test' => 'two')); 
echo $test; // is still 'one' ... render() has its own scope 
+0

嗯..我怎么会注入数据呢? – Matt 2009-08-21 02:35:23

+0

任何数量的方式。字符串是否替换$内容,在包含它之前将全局变量提供给main.php,列表会继续。 – 2009-08-21 03:09:08

+1

我认为这样做不会奏效..在你有机会做字符串替换之前,Include会抛出错误。 – Matt 2009-08-21 22:17:22

1
$contents = htmlentities($contents); 
echo html_entity_decode(eval($contents)); 
+2

为了提高答案的质量,请包括您的帖子如何/为什么会解决问题。 – 2012-10-06 03:29:31

1

你的情况最好的解决办法是结合evaloutput buffer

// read template into $contents 
// replace {title} etc. in $contents 
$contents = str_replace("{title}", $title, $contents); 
ob_start(); 
    eval(" ?>".$contents."<?php "); 
$html .= ob_get_clean(); 
echo html; 
0

据@Josh回答,简单的方法是:

eval('?>'.$htmlandphp);