我需要显示来自其他php文件的html源代码。我有两份文件
code.php
index.php (我希望我能把code.php转换成html源代码。)
code.php:
<!DOCTYPE html> <html> <body> <?php $color = "red"; echo $color; ?> </body> </html>index.php (我希望我能把code.php转换成html源代码。)
$php_to_html = file_get_contents("code.php");
$html_encoded = htmlentities($php_to_html);
echo $html_encoded;但是当我运行index.php文件时,结果是
<!DOCTYPE html> <html> <body> <?php $color = "red"; echo $color; ?> </body> </html>但我希望我能看到结果是
<!DOCTYPE html> <html> <body> red </body> </html>你知道我该怎么做吗,谢谢!
发布于 2017-05-22 23:38:57
您想要执行PHP,所以包含它并捕获输出:
ob_start();
include("code.php");
$php_to_html = ob_get_clean();
$html_encoded = htmlentities($php_to_html);
echo $html_encoded;如果你想把超文本标记语言呈现为超文本标记语言,那么就不要使用htmlentities()。
可选(不是最好的方法),但您可以通过从URL检索来执行它:
$php_to_html = file_get_contents("http://www.example.com/code.php");
$html_encoded = htmlentities($php_to_html);
echo $html_encoded;发布于 2017-05-22 23:41:08
缓冲输出并将其包括在内:
ob_start();
include_once('code.php');
$html = ob_get_clean();通过使用输出缓冲,任何输出都不会发送到浏览器,而是保存在内存中。这允许您运行代码,并以变量的形式获得输出。ob_get_clean()刷新缓冲区(在本例中为我们的$html变量),然后停止缓冲,允许您照常继续。:-)
https://stackoverflow.com/questions/44116895
复制相似问题