2015-07-21 83 views
2

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

我有一个变量叫$ mystic_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> 
+2

mystic_function是'include'。 –

+0

但Include仅包含php文件,但不会执行并存储结果 –

+0

好吧,包括它_does_执行它,但是您将需要使用输出缓冲来保持执行的结果不会以屏幕而不是你的变量。 –

回答

0

您可以使用输出缓冲

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

输出缓冲确实需要使用,但我不认为OP想要修改目标文件。 –

-1

如果使用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); 
-1

例如你有你的功能

php文件PHP类..

<html> 
<head></head> 
<body>@[email protected]</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(@[email protected],@[email protected]); 
    $replacewith = array("Hello Word","Some other stuff"); 

    $mystic_var = str_replace($replacewords, $replacewith); Don't echo inside file - parse it later. 

注意:

PHP函数读取file = file_get_contents();

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

类内部的访问函数=> $ myclass-> readfile(“file.html”);

用str_replace或其他方法解析变量

+0

'file_get_contents'将读取文件,而不是执行PHP。所以返回的内容将有'<?php echo“Hello world”; ?>'而不只是'Hello World'。 –

+0

你是对的 - 文件应该包含php变量,如 @ $ hello_world @ 然后再解析 我将修改我的答案 – SergeDirect