2015-07-21 86 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