首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将html和PHP代码执行到变量中

将html和PHP代码执行到变量中
EN

Stack Overflow用户
提问于 2015-07-21 19:33:23
回答 3查看 476关注 0票数 2

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

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

假设try.php有以下内容:

代码语言:javascript
复制
<html>
<head></head>
<body><?php echo "Hello world"; ?></body>
</html>

然后执行$mystic_var = mystic_function('try.php');然后如果我检查我的$mystic_var,它将有如下所示:

代码语言:javascript
复制
<html>
<head></head>
<body>Hello World</body>
</html>
EN

回答 3

Stack Overflow用户

发布于 2015-07-21 19:38:05

可以使用输出缓冲区。

代码语言:javascript
复制
<?php ob_start(); ?>
<html>
<head></head>
<body><?php echo "Hello world"; ?></body>
</html>
<?php $output = ob_get_clean(); ?>
票数 0
EN

Stack Overflow用户

发布于 2015-07-21 19:49:05

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2015-07-21 19:57:29

例如,函数有一个php类。

php文件。

代码语言:javascript
复制
<html>
<head></head>
<body>@$hello_word@</body> //you should wrap strings you want to play with later into something you parse later
</html>

你们班

代码语言:javascript
复制
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;

   }

}

风景..。

代码语言:javascript
复制
   $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或其他方法解析变量

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31548040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档