Home > Software engineering >  Get HTML content and show this as plain text
Get HTML content and show this as plain text

Time:12-03

I get content of a html file:

ob_start();
include ("myFile.html");
$html = ob_get_contents();

Now I would like to send $html as plain text via mail to show the code. I tried "<pre>".$html."</pre>" and "<code>".$html."</code>"

But I get not the plain code. Can you help me?

CodePudding user response:

Try something like:

<?php

$filePath = __DIR__ . '/myFile.html';

$content = file_get_contents($filePath);
// Escape.
$content = htmlspecialchars($content);
// Makes lines visible.
$content = preg_replace('/\n/', '<br>' . PHP_EOL, $content);

echo $content;

Note that I use single-quotes to improve performance slightly, but when using double-quote, the pattern would be "/\\n/" (to escape Back-slash, but should work even without escaping).

CodePudding user response:

I know Top-Master answered this question, but this is an alternative method, that still uses include. I didn't know enough about PHP to know about the fancy methods, that are probably much more secure.

The <pre> tag doesn't guarantee that the contents will be displayed verbatim. For example <pre><a>Hello</a></pre> will show up as Hello, not <a>Hello</a>. To solve this you can use &lt; (less than sign) and &rt; (greater than sign). If you need and actual ampersand ("&"), you can use &amp;.

This modified version should escape <, >, and &. Do not rely on this in terms of security.

ob_start();
include ("myFile.html");
$html = ob_get_contents();
$html = str_replace("&", "&amp;". $html);
$html = str_replace("<", "&lt;". $html);
$html = str_replace(">", "&gt;", $html);
$html = str_replace("\n", "<br/>");

CodePudding user response:

To show the HTML code in the browser just take readfile() and set the header for Text/Plain.

<?php
header('Content-Type: text/plain; charset=UTF-8');
readfile("myFile.html");

To send HTML code via email, the HTML code can be copied from the browser or can be called up with file_get_contents(). The email format must then be set to plain text.

  • Related