[英]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.