我试图找出如何从类类型控制器执行HTML和PHP代码,并将结果存储到变量中,以模拟一些面向MVC的框架的行为,例如:
我有一个名为 $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>发布于 2015-07-21 19:38:05
可以使用输出缓冲区。
<?php ob_start(); ?>
<html>
<head></head>
<body><?php echo "Hello world"; ?></body>
</html>
<?php $output = ob_get_clean(); ?>发布于 2015-07-21 19:49:05
如果使用file_get_contents,您将从文件中获取所有文本,但是其中的任何PHP代码都不会被执行。如果您include文件,将执行PHP,但是包含该文件的结果将在您的屏幕上结束。您可以使用输出缓冲来保存包含的文件的内容,而不是立即显示它。
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);发布于 2015-07-21 19:57:29
例如,函数有一个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.注意:
函数读取文件= file_get_contents ();
声明类=> $myclass =新的myclass();
=> $myclass->readfile(“file.html”)类中的访问函数;
使用str_replace或其他方法解析变量
https://stackoverflow.com/questions/31548040
复制相似问题