francoleung
francoleung

Reputation: 257

How to convert php code to html source code?

I need to display html source code form other php file. I have two file

code.php

index.php (I hope I can convert the code.php to html source code.)

code.php:

<!DOCTYPE html> <html> <body> <?php $color = "red"; echo $color; ?> </body> </html>

index.php (I hope I can convert the code.php to html source code.)

$php_to_html = file_get_contents("code.php");   
$html_encoded = htmlentities($php_to_html);  
echo $html_encoded;

but when i run the index.php file, the result is

 <!DOCTYPE html> <html> <body> <?php $color = "red"; echo $color; ?> </body> </html>

but I hope I can see the result is

<!DOCTYPE html> <html> <body> red </body> </html>

any idea how can i do this ,thanks!!!

Upvotes: 0

Views: 11146

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 79024

You want to execute the PHP, so include it and capture the output:

ob_start();
include("code.php");
$php_to_html = ob_get_clean();
$html_encoded = htmlentities($php_to_html);  
echo $html_encoded;

If you want the HTML to be rendered as HTML then don't use htmlentities().

Optionally (not the best way) but you can execute it by retrieving from the URL:

$php_to_html = file_get_contents("http://www.example.com/code.php");
$html_encoded = htmlentities($php_to_html);  
echo $html_encoded;

Upvotes: 6

delboy1978uk
delboy1978uk

Reputation: 12382

Buffer output and include it:

ob_start();
include_once('code.php');
$html = ob_get_clean();

By using output buffering, any output is not sent to the browser, but instead kept in memory. This allows you to run the code, and get the output as a variable. ob_get_clean() flushes the buffer (in this case into our $html variable), and then stops buffering, allowing you to continue as normal. :-)

Upvotes: -1

Related Questions