0

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!!!

2
  • 4
    if you just want to see the output of code.php inside of index.php why not just include it? Commented May 22, 2017 at 15:37
  • I want to see the source code of code.php to be html inside of index.php, thx Commented May 23, 2017 at 1:41

2 Answers 2

6

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;
Sign up to request clarification or add additional context in comments.

Comments

-1

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. :-)

1 Comment

From review queue: May I request you to please add some context around your source-code. Code-only answers are difficult to understand. It will help the asker and future readers both if you can add more information in your post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.