【问题标题】:execute html and PHP code into a variable将html和PHP代码执行到变量中
【发布时间】:2015-10-11 10:30:12
【问题描述】:

我试图弄清楚如何从类类型控制器执行 HTML 和 PHP 代码并将结果存储到变量中以模拟一些面向 MVC 的框架的行为,例如:

我有一个名为 $mystic_var 的变量,我想用这个 var 和一个奇怪的函数(我不知道是哪个函数)来读取 .php 文件,执行它并存储结果进入我的 $mystic_var

假设try.php有以下内容:

<html>
<head></head>
<body><?php echo "Hello world"; ?></body>
</html>

然后我执行 $mystic_var = mystic_function('try.php');然后如果我检查我的 $mystic_var,它会是这样的:

<html>
<head></head>
<body>Hello World</body>
</html>

【问题讨论】:

  • mystic_function 是include
  • 但 Include 只会包含 php 文件,但不会执行并存储结果
  • 好吧,包括它确实会执行它,但是您需要使用输出缓冲来防止执行结果出现在屏幕上而不是在您的变量中。

标签: php view controller


【解决方案1】:

你可以使用输出缓冲区

<?php ob_start(); ?>
<html>
<head></head>
<body><?php echo "Hello world"; ?></body>
</html>
<?php $output = ob_get_clean(); ?>

【讨论】:

  • 确实需要使用输出缓冲,但我认为OP不想修改目标文件。
【解决方案2】:

如果您使用file_get_contents,您将从文件中获取所有文本,但不会执行其中的任何 PHP 代码。如果你include 文件,PHP 将被执行,但包含文件的结果最终会出现在你的屏幕上。您可以使用output buffering 来保存包含文件的内容,而不是立即显示它。

function mystic_function($php_file) {
    ob_start();
    include $php_file;
    return ob_get_flush();
}

$mystic_var = mystic_function('try.php');

echo $mystic_var;
// or if you want to see the html
// echo htmlspecialchars($mystic_var);

【讨论】:

    【解决方案3】:

    例如,你的函数有一个 php 类

    php 文件..

    <html>
    <head></head>
    <body>@$hello_word@</body> //you should wrap strings you want to play with later into something you parse later
    </html>
    

    你的班级

    class myclass{
    
       // and you have your php function that returns the file contents..
    
        public function readfile($a){  //$a will store file path & name
    
            $contents = file_get_contents ($a);
            return $contents;
    
       }
    
    }
    

    视图...

       $myclass = new myclass();
    
        $mystic_var = $myclass->readfile("file.html"); // file contents saved in variable
        $replacewords = array(@$hello_word@,@some_other_stuff@);
        $replacewith = array("Hello Word","Some other stuff");
    
        $mystic_var = str_replace($replacewords, $replacewith ); Don't echo inside file - parse it later.
    

    注意:

    读取文件的PHP函数 = file_get_contents();

    声明 class=> $myclass= new myclass();

    1234562里面的访问函数 => $myclass->readfile("file.html");

    用str_replace或其他方法解析变量

    【讨论】:

    • file_get_contents 将读取文件,而不是执行 PHP。所以返回的内容将有&lt;?php echo "Hello world"; ?&gt; 而不仅仅是Hello World
    • 你说得对 - 文件应该包含 php 变量,用 @$hello_world@ 之类的东西包装,然后再解析我会修改我的答案
    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多