Output rendered HTML as plain text

maxxon15 picture maxxon15 · Nov 20, 2014 · Viewed 19.1k times · Source

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?

Answer

Nimeshka Srimal picture Nimeshka Srimal · Nov 20, 2014

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);