Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output rendered HTML as plain text

I trying to show the rendered output thrown by a PHP file as text.

The text should contain the HTML tags as well.

Something like what you'd get when you do a "View Source" on a web page.

How can I achieve this?

like image 254
maxxon15 Avatar asked Nov 20 '14 08:11

maxxon15


3 Answers

Since you have mentioned that you want the output to be like viewing the source, you can simply declare the content type as plain text at the beginning of your script.

This will render the output as text, and the text file is downloadable.

Ex:

<?php
header("Content-Type: text/plain");
echo '<html><head><title>Hello</title></head><body><p>helloooooo</p></body></html>';
echo $_SERVER['REMOTE_ADDR'];
?>

Hope this will make sense, or else if you want to display this to the user, an alternative way would be to pass the output through htmlspecialchars(); function.

Ex:

$content = '<html><head><title>Hello</title></head><body>p>helloooooo</p></body></html>';
echo htmlspecialchars($content);
like image 116
Nimeshka Srimal Avatar answered Nov 14 '22 04:11

Nimeshka Srimal


try using php's show_source(); function.

give it a link to your text file e.g.

show_source("/link/to/my_file.html");

and be careful with it because it can expose passwords and other sensitive information

like image 36
hackitect Avatar answered Nov 14 '22 05:11

hackitect


To do this, the easiest way is to capture everything which is sent to the output and buffer it. At the end you can decide whether you want to render it just like you always do, or whether you want to use htmlspecialchars() to display the source.

At the start of your code, place the following statement:

$outputType = 'viewsource';
ob_start();

At the end of your code, add the following:

$output = ob_get_contents();
ob_end_clean();
if($outputType == 'viewsource') {
    echo htmlspecialchars($output);
} else {
    echo $output;
}
like image 1
RichardBernards Avatar answered Nov 14 '22 05:11

RichardBernards