[英]How to convert php code to html source code?
我需要从其他 php 文件中显示 html 源代码。 我有两个文件
代码.php
index.php(希望能把code.php转成html源代码。)
代码.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>
知道我该怎么做,谢谢!!!
您想执行 PHP,因此包含它并捕获输出:
ob_start();
include("code.php");
$php_to_html = ob_get_clean();
$html_encoded = htmlentities($php_to_html);
echo $html_encoded;
如果您希望将 HTML 呈现为 HTML,则不要使用htmlentities()
。
可选(不是最好的方法),但您可以通过从 URL 检索来执行它:
$php_to_html = file_get_contents("http://www.example.com/code.php");
$html_encoded = htmlentities($php_to_html);
echo $html_encoded;
缓冲输出并包含它:
ob_start();
include_once('code.php');
$html = ob_get_clean();
通过使用输出缓冲,任何输出都不会发送到浏览器,而是保存在内存中。 这允许您运行代码,并将输出作为变量。 ob_get_clean() 会刷新缓冲区(在这种情况下是到我们的 $html 变量中),然后停止缓冲,让您可以正常继续。 :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.