The result was outputting HTML as plain text

I am trying to show the output output generated by a PHP file as text.

The text must also contain HTML tags.

Something like what you would get when you "view source" on a web page.

How can I achieve this?

+3


source to share


5 answers


Since you mentioned that you want the result to look like a view of the source, you can simply declare the content type as plain text at the beginning of your script.

This will make the output as text and the text file will be loaded.

Example:

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

      



Hopefully this makes sense, otherwise if you wanted to display this to the user, an alternative way would be to pass the result through htmlspecialchars (); function.

Example:

$content = '<html><head><title>Hello</title></head><body>p>helloooooo</p></body></html>';
echo htmlspecialchars($content);

      

+5


source


To do this, the easiest way is to capture whatever is sent to the output and buffer it. In the end, you can decide if you want to display it the same way as always, or if you want to use it htmlspecialchars()

to display the source.

Place the following statement at the beginning of your code:

$outputType = 'viewsource';
ob_start();

      



At the end of the code, add the following:

$output = ob_get_contents();
ob_end_clean();
if($outputType == 'viewsource') {
    echo htmlspecialchars($output);
} else {
    echo $output;
}

      

+1


source


try using php function show_source (); ...

give a link to your text file eg.

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

      

and be careful with it , as it can expose passwords and other confidential information

0


source


There are several ways to do this, the easiest is to use tags pre

, or you can rename your file from .php

to .phps

or use highlight_file($file)

which syntax will highlight your code as well. There's also file_get_contents()

and even show_source()

as @hackitect mentioned in the description.

Remember that any html code must be rendered in tags pre

and escaped.

0


source


Another trick I actually used was to link to a hyperlink with the URL of the view source.

Works great on Chrome, Firefox and Opera, but not IE.

<a target="_blank" href="view-source:http://stackoverflow.com/questions/27034642/output-rendered-html-as-plain-text">Get Plain Text</a>

0


source







All Articles